简体   繁体   中英

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.

This is how Java in Practice says to do singletons:

  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. One thing he points out is that if you want your Singleton to be serializable you can't just implement Serializable. You need to override the readResolve method as well. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM