Q
Problem solve Get help with specific problems with your technologies, process and projects.

Writing a class

How can we write a class which can only be instantiated once?
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()
   {
   }
}

Dig Deeper on Topics Archive

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchAWS

SearchCloudComputing

TheServerSide.com

Close