关于在Java中实现Singleton模式,我有一些问题。
发布于 2015-05-07 12:45:44
( 1)不要使Singleton克隆,也没有人会克隆它
2)如果Singleton是Serialiazable的,并且它不使用readResolve来防止重复,那么在反序列化它时就会得到副本,并且它不再是Singleton了。影响取决于应用程序逻辑。
发布于 2015-05-07 12:53:23
有效的Java项目3: Elvis是您的类。
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public static Elvis getInstance() { return INSTANCE; }
public void leaveTheBuilding() { ... }
}如果您想序列化它:
// readResolve method to preserve singleton property
private Object readResolve() {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}或者你可以用枚举:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}发布于 2015-05-07 12:47:11
我不确定你的第二点,但这回答了第一点:
public class SingletonObject {
/**
* The one and only instance of this class
*/
private static SingletonObject ref;
/**
* Creates the object. Must not be called more than once.
*/
private SingletonObject() {
// no code required
}
/**
* Returns a reference to the singleton object
* @returns The singleton object
*/
public static synchronized SingletonObject getSingletonObject() {
if (ref == null) {
// First call, so create it
ref = new SingletonObject();
}
return ref;
}
/**
* Prevents cloning of the object.
* @throws CloneNotSupportedException If method is called
*/
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}您可以简单地重写克隆方法。请注意,getSingletonObject是同步的,如果ref等于null,两个线程同时调用函数,这将阻止创建对象的实例。
https://stackoverflow.com/questions/30101354
复制相似问题