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 first published in August 2004

Dig deeper on Java Web Services

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

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.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close