質問

So we were recently introduced to the Singleton Pattern, and I've found a lot of great uses for it since, but there's just one really small thing that bugs me about it. I've noticed that in every example I've seen for the singleton pattern,the standard getInstance() method looks like this:

    private static Singleton instance = null;

    public static Singleton getInstance() {
    if ( instance == null ) 
        instance = new Singleton();
    return instance;
}

The thing I want to know is, is there a point in checking if the instance variable is null?

Would it work if you just assigned the instance variable to a new Singleton instance straight away and just return it like this:

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
    return instance;
}

Sorry if this seems like a waste of time of a question, but I just wanted to know if there was any reason as to why the first example is use everywhere.

Thanks for your time.

EDIT: Forgot to make the methods static.

役に立ちましたか?

解決

Both are valid ways of creating a Singleton instance. The former is called lazy initialization and the latter is called eager initialization

Lazy initialization will help if the cost of creation of singleton instance is high. In this case the singleton instance is created only when its required.

On the other hand, eager initialization is by default Thread-safe

他のヒント

The 1-st example (lazy load) is not thread safe; to make it thread safe you can put it

    private static volatile Singleton instance = null;
    private static final Object syncObj = new syncObj();

    public static Singleton getInstance() { // <- do not forget "static"
      // Double checked locking pattern
      if (instance != null) 
        return instance;

      synchronize(syncObj)  {
        if (instance != null) 
          return instance;

        instance = new Singleton();
      }

      return instance;
   }

The second example (eager load) is thread safe:

  // "final" looks good here
  private static final Singleton instance = new Singleton();

  public static Singleton getInstance() { // <- do not forget "static"
    return instance;
  }

In the first example you only create an instance of the class when you really need it (lazy initialization) the first time. So, you are using less memory until you need the class.

If you have a lot of Singleton, you are saving memory and time if you finally don't need them.

First example is a lazy loading of instance creation where first request to getInstance method create the Instance.

To avoid multiple object creation using lazy loading at first time method call (from multiple thread at same time), Object creation must be synchronized.

if (null == instance ) {
    synchronized (Singleton.class){
        if (null == instance ) {
            instance = new Singleton();
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top