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.

6 comments:

  1. many thanks for this helpful material

    ReplyDelete
  2. I go by using an enum... clean but confusing.
    check out this link for a thorough discussion on many other ways:
    http://yohanliyanage.blogspot.com/2009/09/breaking-singleton.html

    a word of caution though, this is good knowledge for theory, its an unnecessary pain while implementing.

    ReplyDelete
  3. set contructor in private method and when create a instance from object we will check that if the state of object is null. is that right :)

    ReplyDelete
  4. I think you mean the same as to what is given in the article above

    ReplyDelete
  5. Thank you so much it was a great guide, now to make a class singleton? is without a doubt simple and easy by using your information. Thank you

    ReplyDelete