View RSS Feed

My Java Tips

Singleton Pattern

Rate this Entry
by , 11-08-2011 at 05:51 PM (868 Views)
A design pattern describes a proven solution to a recurring problem or in other words it is a template for solving problems. Singleton pattern is a creation pattern.

As the name denotes there will be only an instance of an object, which is created by this pattern. For example: central configuration object should have only one instance that should be accessible from other parts of application. If we have more than one instances of a central configuration object, then different parts of application will be accessing different configuration object which makes no sense.


Implementation of singleton is simple in Java. Firstly, we have to prevent direct initialization of the class. We created a static method called " getSingletonObject() " that checks if an instance of the class exists or not. If not, it creates a new instance and keep it in ref which is of type singletonObject. In other case (instance of class exists), our method will just return already existing instance.

Secondly, we have to take care of multiple threads accessing the method " getSingletonObject() " at the same time. Lets assume that 2 threads call the SingletonObject constructor at the same time, then both will get different instances of the class which is not what we need. The solution to this is to make method getSingletonObject() synchronized.

Lastly, we have to override clone method because a developer can call " clone " method to get a copy of object which is clear violation of singleton. We will add a " clone() " method in our class, and throw a " CloneNotSupportedException ", If anyone tries to clone object of SingletonObject. Review the code below:

Java Code:
public class SingletonObject
{
  private SingletonObject()
  {
  }

  public static SingletonObject getSingletonObject()
  {
    if (ref == null)
        // can call this constructor
        ref = new SingletonObject();
    return ref;
  }

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

  private static SingletonObject ref;
}

Submit "Singleton Pattern" to Facebook Submit "Singleton Pattern" to Digg Submit "Singleton Pattern" to del.icio.us Submit "Singleton Pattern" to StumbleUpon Submit "Singleton Pattern" to Google

Tags: None Add / Edit Tags
Categories
Design Patterns , Java SE

Comments