Wednesday, April 18, 2012

Singleton Design Pattern example

Singleton is the simplest design pattern and very easy to remember. As the name suggest singleton, it is used to ensure that a class has a single instance and provide a global point of access to it. Use Singleton Pattern when there must be exactly one instance of class,and it must be accessible to clients from well known access point.

The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.

Singleton Examples :

Clipboard Class for providing application specific copy-and-paste functionality

Step by step process to create a Singleton class.

Lets say we have a class Clipboard.java as shown below

public class Clipboard {
 private String copy;
 private String paste;

 //..
}

Client code can create as many instance as required

Clipboard instance1 = new Clipboard();
Clipboard instance2 = new Clipboard();

Now the question is How do we prevent clients from creating multiple objects? For this we can have a private constructor so that it cannot be subclassed or object cannot be created from codes outside this class.

public class Clipboard {
 private String copy;
 private String paste;
 
 private Clipboard() {

 }
 //..
}

Then how do we ensure the clients get a single instance of his class instantiated and access it? We can have a static Clipboard instance declared and a static getInstance() method which will return Clipboard object.

Lets see the complete code.

public class Clipboard {
 private String copy;
 private String paste;

 private static Clipboard instance;
 
 private Clipboard() {

 }

 public static Clipboard getInstance() {
  if(instance == null) {
   instance = new Clipboard();
  }
  return instance;
 }
 //..
}

It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.

@Override
protected Object clone() throws CloneNotSupportedException { 
 throw new CloneNotSupportedException("Clone is not allowed.");     
} 


To avoid thread safety issues, you can also implement as shown below.

public class Clipboard {
 private String copy;
 private String paste;

 private static final Clipboard INSTANCE = new Clipboard();
 
 private Clipboard() {

 }

 public static synchronized Clipboard getInstance() {
  return INSTANCE;
 }
}