How can we write a class which can only be instantiated once?

    Requires Free Membership to View

This is typically facilitated with the use of the Singleton pattern (see http://c2.com/cgi/wiki?SingletonPattern). The following example illustrates one implementation suggestion in Java:

public class MySingleton
{
   static private MySingleton instance = null;
 
   static public MySingleton getInstance()
   {
      if (null == instance)
      {
         instance = new MySingleton();
      }
      return instance;
   }

   // The constructor is made private to prevent direct instantiation
   // of this class from external objects.
   private MySingleton()
   {
   }
}

This was first published in August 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.