Saturday, 15 November 2014

Design Pattern - Singleton

Singleton is simple pattern which guaranty  only one instance of object is present. Singleton is term taken from mathematical concept "Singleton is a set with exactly one element"

Singleton is achieved in java by

  1. By making default constructor private - hence you can not initialised the class .

  2. Having static method that can return you instance - control over how to create object

  3. Having self instance private static and volatile - Thread safe unique instance.


Note: volatile from Java 5 means value of variable will not be tread-locally cached. Value will be updated directly in main memory. Variable will act like its synchronised on its self.

Below is sample for double check singleton:
public class Singleton {
private volatile static Singleton INSTANCE;

private Singleton() {

}

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

Reference:  WikiHead First Design Patterns

No comments:

Post a Comment