开发者

Singleton design pattern which to be used when? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.
// Lazy Initialization 

Public MySingleton{
    private static mySingleton = null;

    Public Static getInstance(){
       if(null == mySingleton ){
            mySingleton = new MySingl开发者_如何学Pythoneton();
       }

       return mySingleton;
    }
}

// Eager Initilization 

Public MySingleton{
    private static mySingleton = new MySingleton();

    Public Static getInstance(){
        return mySingleton ;
    }
}

}


Both are incorrect. You should follow the example set in Joshua Bloch's "Effective Java", explained here, based on enum.


As java has moved in the direction of dependency injection, I've seen less and less explicit singletons like what is described above. This is because when an IOC container instantiates an object it's by default a singleton.


The first is an attempt at optimization:

  • If you know your code takes a long time to initialize, but is rarely used, you should use lazy.
  • If you know your code takes a long time to initialize, but is not used till quite a while later in the program, use lazy.
  • If profiling reveals under rare circumstances the singleton is actually used, use lazy.

There's more situations... this should give you a start.


Your first example is not a singleton at all. It returns a new instance on every call!

That said, which is "better" (lazy vs. eager) really depends on your circumstances. Lazy is more complicated, which is its main liability.


Use an enumeration.

   public enum Foo {
       INSTANCE;
   }  

Read this from Effective Java,

"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."


The best way to avoid duplicates with a singleton is to do the following:

public final MySingleton {

  //this will be instantiated at class loading time, thus insuring more than one thread
  //won't get separate instances.
  private static final MySingleton INSTANCE = new MySingleton();

  private MySingleton() {
    //empty for this example.
  }

  public static MySingleton getInstance() {
    return INSTANCE;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜