我在探索单例设计模式,我开发了一个类...
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () { //private constructor
}
public static synchronized SingletonObject getSingletonObject() {
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException ();
}
}
但是同步的成本非常高,所以我转而采用新设计的热切创建实例,而不是懒惰创建的实例。
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return uniqueInstance;
}
}
但是请告诉我第二种设计比以前的设计有什么优势..!!
最佳答案
Josh Bloch 建议使用枚举:
public enum Foo {
INSTANCE;
}
有关解释,请参阅他的 Effective Java Reloaded在 Google I/O 2008 上发表演讲。
总结:
"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."
关于java - 关于单例设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250799/