Ask the Expert

Writing a class

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
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
Sort by: OldestNewest

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: