Tuesday, May 1, 2012

Singleton Design Pattern

The right way to implement a Singleton Design Pattern, also written out by researcher Bill Pugh. Two major changes to keep in mind -

1. Make the initialization as lazy as possible.
2. Get rid of the issues of synchronized access.

Way to implement -

  1. Declare a public class, name it as Singleton.
  2. Create a private constructor for this class.
  3. Create an inner class which holds the singleton instance, make it private and static.
  4. Create a Singleton instance variable in inner class make it private, static and final and load new Singleton instance.
  5. Create a public static method in Singleton class to return the instance of Singleton class.


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 {
    private static final Singleton INSTANCE = new Singleton();
  }

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

No comments:

Post a Comment