Saturday, August 3, 2013

Singleton pattern : The Good, Better and Best ways of implementation

In software industry the term "singleton" is associated with design pattern. It is mainly used when you need a single instance of a class to coordinate actions across the system. For instance, in the database driven applications you never want to request DB to open a connection for each subsequent operations. Instead you want to open only one connection during the first request and the next subsequent requests will use that connection to perform DB operations. To serve this purpose singleton pattern is quite handy. For having the deeper understanding of this pattern, you just need to have the knowledge of "static" construct and a basic knowledge on threading.
The good:
public class SingletonObject
{
    private SingletonObject()
    {
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null) {
         synchronized (SingletonObject .class) {
            ref = new SingletonObject();
         }
      } 
      return ref;
    }

    private static volatile SingletonObject ref;
}
The good ++:
public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      return ref;
    }

    private static final SingletonObject ref = new SingletonObject();
}
The better: This technique doesn't require any special language constructs. So on that point of view this is better!
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;
        }
}
The best:
public enum SingletonObject { 
    INSTANCE;
}
According to Joshua Bloch:"a single-element enum type is the best way to implement a singleton for any version of Java that supports enum. This is concise and has no drawbacks regarding serializable objects which is challenging for other implementations.

No comments:

Post a Comment

SyntaxHighlighter