[英]If not for lazy initialisation, is there any advantage of building singleton using method rather than static class member?
Very often I see singleton built in this way: 我经常看到单例以这种方式构建:
public static MyClass instance() {
if (singleton == null) {
singleton = new MyClass();
}
return singleton;
}
If not for the lazy initialization effect, does the approach have any advantage over simply declaring a static instance like this? 如果不是出于延迟初始化的效果,那么这种方法是否比简单地声明一个静态实例具有任何优势?
public final static MyClass singleton = new MyClass();
No, in fact the other approach, ie: 不,实际上是另一种方法,即:
public final static MyClass singleton = new MyClass();
might be better as, if you you have 2 threads calling the instance method at the same time you could get a race condition. 可能会更好,因为如果您有2个线程同时调用实例方法,则可能会获得竞争条件。
This is how Java in Practice says to do singletons: 这是Java在实践中说做单例的方式:
private final static MyClass _instance = new MyClass();
public static MyClass getInstance() {
return _instance;
}
private MyClass() {}
Update Since @jon-skeet mentioned it there is really good discussion of Singletons in the book Effective Java by Joshua Block. 更新由于@ jon-skeet提到了它,Joshua Block撰写的有效Java一书中对Singleton的讨论非常好。 One thing he points out is that if you want your Singleton to be serializable you can't just implement Serializable.
他指出的一件事是,如果您希望Singleton可序列化,则不能仅仅实现Serializable。 You need to override the readResolve method as well.
您还需要重写readResolve方法。 Use the above approach makes this easy:
使用上述方法使此操作变得容易:
private Object readResolve() throws ObjectStreamException {
return _instance;
}
Update 2 : Checkout this excellent discussion on Singletons linked to by @mardavi: http://en.wikipedia.org/wiki/Singleton_pattern#Initialization_On_Demand_Holder_Idiom 更新2 :通过@mardavi链接查看关于Singletons的精彩讨论: http : //en.wikipedia.org/wiki/Singleton_pattern#Initialization_On_Demand_Holder_Idiom
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.