J***e 发帖数: 50 | 1 Write a special singleton class, the class has one integer field,
make sure only one instance of this class will be instantiated for
the same value of the integer field.
以下是我写的, 但是有个问题,这样instance不是static, getInstance()因为用到
instance也不能是static,可以吗?这样解对吗?另外,当singleton object destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()?
import java.util.HashMap;
public class SingletonInteger {
private Integer value;
private SingletonInteger instance;
private static HashMap values;
private SingletonInteger(Integer val)
{
value=val;
}
public synchronized SingletonInteger getInstance(Integer v)
{
if(values==null)
{
values = new HashMap();
}
if(values.containsKey(v)==false)
{
instance = new SingletonInteger(v);
values.put(v,instance);
}
return values.get(v);
}
} | f*********5 发帖数: 576 | 2 why you need instance here?
simply remove it and make the getInstance static
public static RemoveInstance(int i)
{
values[i].~SingletonInteger();
values.erase(i);
}
destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()?
【在 J***e 的大作中提到】 : Write a special singleton class, the class has one integer field, : make sure only one instance of this class will be instantiated for : the same value of the integer field. : 以下是我写的, 但是有个问题,这样instance不是static, getInstance()因为用到 : instance也不能是static,可以吗?这样解对吗?另外,当singleton object destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()? : import java.util.HashMap; : public class SingletonInteger { : private Integer value; : private SingletonInteger instance; : private static HashMap values;
|
|