Design Patterns - Part Three: Singleton

Design Patterns – Part Three: Singleton

Today I will describe the Singleton pattern, one of the simplest, yet generating active discussions all over the net. Some people consider it to be an antipattern. We have many different flavours of this pattern, singleton can be thread safe, lazy loaded, eagerly loaded, implemented as a static class or enum.
Simple thread safe implementation:

/**
 * This solution uses class loading mechanizm and its
 * thread safe
 * @author kris
 * @version 01-02-2011
 */

public class FirstSingleton {
    static class FirstSingletonHolder {
        static final FirstSingleton INSTANCE = new FirstSingleton();
    }
    public static FirstSingleton getInstance() {
        return FirstSingletonHolder.INSTANCE;
    }
}

Simple lazy loading implementation:

/**
 * Lazy loaded version of singleton pattern
 * @author kris
 * @version 01-02-2011
 */

public class SecondSingleton {
        private static SecondSingleton instance = null;

        private SecondSingleton() {}

        public static SecondSingleton getInstance() {
              if(null == instance) {
                  synchronized(SecondSingleton.class) {
                      if(null == instance) {
                          instance = new SecondSingleton();
                      }
                  }
               }
               return instance;
        }

        protected Object clone() throws CloneNotSupportedException {
            throw new CloneNotSupportedException();
        }
}

Enum implementation of Singleton pattern (according to J.Bloch the best implementation availalble)

“This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.”

/**
 * Enum implementation of singleton design pattern
 *
 * @author Krzysztof Grajek
 * @version 01-02-2011
 */

public enum EnumSingleton {
    INSTANCE;

    private String name;

    public String getName(){
        return name;
    }
}

If you feel that singleton is the right solution to your problem, use the one which is shortest/simplest and available in your environment (enum version J2EE 5+)

One response on “Design Patterns – Part Three: Singleton

  1. Sandeep February 1, 2011 at 8:43 pm

    1) Someone reading this post may also like to see a lazy but threadsafe approac at http://extreme-java.blogspot.com/2010/08/what-is-singleton-pattern-and-how-to.html

    2) You need not override clone method in second example code above. The inherited clone is anyway same as you have written.

Leave a Reply