Singleton Design Pattern

Creational Design Pattern

Summary
Singleton Design pattern is used to provide a mechanism so that a Class can have only one instance. So when Client try's to use an instance of Singleton Class it gets the same instance. 
Singleton.

Details
Singleton Design pattern make sure that Class which implement this pattern can have only one instance. In case of Java, only one instance in a single JVM.
For instance if we want only one instance of Cache Class which would store temporary values in memory.

Singleton pattern is also used in Logger Classes. Logger provide single instance for logging which is used by application code.

Singleton design pattern is implemented by following mechanism
1) Making the constructor private. So that Client cannot create different instances
2) Provide a static method, which the client will interact to get the instance of the class
3) Do not offer any setter method for the object
4) If any getter for individual property returns any object reference, it should return a copy of it
5) Taking care of reflection api, to do this we can throw exception in the constructor if it the instance is not initialized.

Advantages
Provide an option to make sure the instance is single, and if we want to create multiple copies of the object still they will be same.

Useful when we want only one instance of a Class like Service, shared resource etc.

Disadvantages
Depending on the need, DI/IOC can be better suitable.

Possible ways to break

Following points need to be thought about possible ways to break the Singleton Class to get more than one instance.

In java one can use the Reflection API to alter the constructor (private) of the Singleton Class to create different instances. This can be taken care by throwing exception from the private constructor.

In Java one can use the clone. It can be achieved by overriding clone() method and throwing Exception.

Multiple thread can break the Singleton Class. It needs to be taken care as well.

In Java Serialization can cause breaking this contract. It can be handled by returning the instance from readResolve() method.
Example
Let's take example of a House Key. We want only one key for the whole house. We do not want any way to temper the key. We want only one identical key to be available. If any one needs a key, essentially they will get the same single key instance. We can utilize the Singleton pattern to make sure that the key once generated is not modifiable.

Here the Class HouseKey implements Singleton pattern, and that Class make sure only one instance of the key exists.

Class Diagram

Sample Code


public class HouseKey implements Serializable {
  private static final long serialVersionUID = 1L;
  private String keyPattern;
  private Long keyDate;

  private static HouseKey instance;

  // private constructor
  private HouseKey() {

  }

  // public get instance method
  public static HouseKey getInstance() {
    if (instance == null) {
      synchronized (HouseKey.class) {
        instance = new HouseKey();
        instance.keyPattern = "key 12345";
        instance.keyDate = new Date().getTime();
      }
    }
    return instance;
  }


  // safeguard against Clone
  protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }


  // safeguard against Serialization
  public Object readResolve() {
    return HouseKey.getInstance();
  }

  @Override
  public String toString() {
    return "HouseKey " + this.keyPattern + "  " + this.keyDate;
  }
}

Github Code 
References

Comments

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized