Monday, February 28, 2011

Implementation of Singleton design pattern

I will explain the implementation with the following steps

Step 1: Provide a default Private constructor

public class SingletonDemo{

// Note that the constructor is private
private SingletonDemo() {
// Optional Code
}
}


Step 2: Create a Method for getting the reference to the SingletonDemo



public class SingletonDemo {

private static SingletonDemo singletonDemo;
// Note that the constructor is private
private SingletonDemo() {
// Optional Code
}
public static SingletonDemo getSingletonDemo() {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
}
Then write a public static getter or access method to get the instance of the SingletonDemo Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method(getter) Synchronized to prevent Thread Problems.

public static synchronized SingletonDemo getSingletonDemo()

It might happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle.
In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonDemo clonedObject = (SingletonDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

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

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class SingletonClass {

private static SingletonClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}
public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// SingletonClass obj = new SingletonClass(); //Compilation error not allowed
SingletonClass obj = SingletonClass.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}



cheers,
Varaprasad.

No comments: