Q

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()
   {
   }
}

This was last published in August 2004

Dig Deeper on Java Web Services

PRO+

Content

Find more PRO+ content and other member only offers, here.

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.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close