Singleton Design Pattern | One Instance, Everyone Cares

I have used Spring Framework a lot & hence was always closer to Singleton Design Pattern. So what does Singleton Design Pattern mean?

GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.

Above definition seems to be very simple in saying only two points,

  • There should be only one instance allowed for a class and
  • We should allow global point of access to that single instance.

Now, the trickier part is implementation and management of that single instance. Yes, I must say, it is a bit difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance in various languages.

The security of the single instance is specific to the language used.

Java Sample for Singleton Design Pattern

Here are the rules I follow to create a singleton class.

  • Suppress the constructor and make it private. Don’t allow even a single instance for the class.
  • Declare an attribute for that same class.
  • Provide a global method for accessing the instance
public class Singleton {
  private static Singleton singleInstance;
  private Singleton() {//Private constructor}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }

There are various other considerations we need to take into account based on specific language API’s & constructs to make achieve the behaviour suggested. I’m detailing below the use cases for JAVA.

1. Eager and Lazy Instantiation in Singleton Pattern

You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues.

The above code is a sample of lazy instantiation for singleton design pattern.
The single instance will be created at the time of first call of the getSingleInstance() method.
We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class, which is called eager instantiation. It also takes care of the multithreading scenario.

public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {//Private constructor}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}
2. Cloning can spoil the game

Although we have taken enough precaution to make the Singleton object work as singleton, Cloning the object can still copy it and result into duplicate object. The clone of the singleton object can be constructed using clone() method of the object. Hence it is advisable to overload clone() method of Object class and throw CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
}
3. Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated.
You can serialize and de-serialize and get a new instance of the same singleton class.
Using java api, you can implement the below method and override the instance read from the stream.

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

This was the simplest example of creating a Singleton Class in your application. I’ll suggest you try out a simple example of this by yourself & test it via main().

You just read a fact!

Advertisements