Showing posts with label Singleton Class. Show all posts
Showing posts with label Singleton Class. Show all posts

Wednesday, February 17, 2010

How to make a class singleton?

I have been wondering about the ways a class can be made singleton. One way I know of is to make the constructor of the class private. Add another method in the class which would first check if an instance of the class exists or not. In case it exists, it returns the same instance else creates a new instance.


public class MyClass {

         private static MyClass myClassInstance;

         public static MyClass getInstance()
        {
             if(null== myClassInstance )
            {
                   myClassInstance = new MyClass ();
            }
           return myClassInstance ;
        }

        private MyClass () {
        }

}


Guys, Please share if you know any other way of making a class singleton.