Thursday, November 17, 2011

Singleton Creational Design Pattern




Singleton is most commonly used creational design pattern. As name says, there is only one instance of an object created by the JVM in the application. I.e. This pattern restricts instantiation of class to one object.

Implementation:

public class Singleton {
      // Private constructor prevents instantiation from other classes
      private Singleton() {
      }

      /**
       * SingletonHolder is loaded on the first execution of
       * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
       * not before.
       */
      private static class SingletonHolder {
            public static final Singleton instance = new Singleton();
      }

      public static Singleton getInstance() {
            return SingletonHolder.instance;
      }
}

Instructions:
1.    Constructor need to be marked as private to stop creating instance externally.
2.    Singleton not supposed to implement clone method.
3.    Implement clone method if it’s super class implementing the clone method.
Implementation of clone method:
public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}
4.    Instance need to be assigned to variable to avoid thread safety issues.
5.    Holder need to be implemented to support lazy-loading.

No comments:

Post a Comment