Many people consider the singleton an anti-pattern. Many others think it's part of the creational patterns family. I don't care about its definition and I think a singleton can be useful sometimes in the real world! Singleton design pattern is used when you want to have only one instance of a given class. Let's see some Java implementations:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance(){
return INSTANCE;
}
}
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
public class LazyDoubleCheckedLockingSingleton {
private static volatile LazyDoubleCheckedLockingSingleton instance;
/** private constructor to prevent others from instantiating this class */
private LazyDoubleCheckedLockingSingleton() {}
/** Lazily initialize the singleton in a synchronized block */
public static LazyDoubleCheckedLockingSingleton getInstance() {
if(instance == null) {
synchronized (LazyDoubleCheckedLockingSingleton.class) {
// double-check
if(instance == null) {
instance = new LazyDoubleCheckedLockingSingleton();
}
}
}
return instance;
}
}
public class LazyDoubleCheckedLockingSingleton {
private static volatile LazyDoubleCheckedLockingSingleton instance;
/** private constructor to prevent others from instantiating this class */
private LazyDoubleCheckedLockingSingleton() {}
/** Lazily initialize the singleton in a synchronized block */
public static LazyDoubleCheckedLockingSingleton getInstance() {
if(instance == null) {
synchronized (LazyDoubleCheckedLockingSingleton.class) {
// double-check
if(instance == null) {
instance = new LazyDoubleCheckedLockingSingleton();
}
}
}
return instance;
}
}