dimanche 13 décembre 2015

What is the use of checking for object uniqueness in Singleton pattern?

In singleton pattern, we have a private constructor and a public static method like below -

public class MyClass
{
     private static MyClass _uniqueInstance;
     private MyClass()
     { 
     }
     public static MyClass GetInstance()
     {
         if(_uniqueInstance==null)
         { 
               _uniqueInstance  =  new MyClass();
         }
     return _uniqueInstance;
     }
}

And we can create ONE and Only ONE instance of this Class by invoking the static method whenever we need the object of this class like -

var myObject = MyClass.GetInstance();

But I am confused why we check for null in the GetInstance() method as the "_uniqueInstance" is already a static variable, so it will be initailized and allocated memory only once . Even if we do not check for null and still initialize the object with "new", memory will not be allocated again for this object as it is a static variable. So, what is the use of this null check ? Please clear my doubt.

Aucun commentaire:

Enregistrer un commentaire