Singleton Design Pattern

Singleton design pattern is a creational design pattern that restricts the initialization of objects. This pattern ensures that at any point of time there is only one instance of the object within the application context. And the singleton design  also pattern requires that there should be a global point to access the object.

Singleton design pattern should provide the flexibility of creating multiple instances if the situation demands at a later stage, without affecting classes that are using the singleton object.

Any fields defined in the singleton class would act as static fields; as only one instance of the class would be created. Singletons can be used in place of the global variables.

The singleton pattern may be used for an application wide resource, like the logger or implement a state object.

Implementing Singleton Design Pattern

To implement the singleton design pattern, you need to:

  1. Declare the constructor of the class as private so that the class cannot be instantiated by any other class.
  2. Declare a public static method to get the instance of the class, so that the method that method can control the number instance that can be created. The method should also be thread safe.

Example of a Singleton class

public class MySingleton {
  private static MySingleton instance;

  // Private Contructor
  private MySingleton() {
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (instance == null) {
      instance = new MySingleton();
    }
    return instance;
  }
}

The above example uses the lazy initiation as the instance of the class would not be created until the getInstance() method is called for the first time.

Cloning can create problems as will allow you create a copy of the singleton object. Thus to avoid cloning the clone() method should be overridden.

public Object clone() throws CloneNotSupportedException {

      throw new CloneNotSupportedException();

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s