You are on page 1of 12

Singleton Pattern

In next 15 minutes…
• What
• Where
• How
What is Singleton?

Ensure that a class can have


only one instance, and provide a
global point of access to it
[Gof]
Where to use it?
• Loggers
• Device driver modules
• Communication end points
• Handling database connections
• DON’T USE IT!!!
Evil Singleton
• Difficult to find dependencies
• Breaks inheritance
• Hampers code testability

• Use DI instead.
How to create one?
• Eager loading
• Lazy loading
• Double Checked Locking
• Lazy Holder class
• Single Element Enum
Eager Loading
public class Singleton {

private static final Singleton INSTANCE = new


Singleton();

private Elvis() {}

public static Singleton getInstance() {


return INSTANCE;
}
}
Lazy Loading
public class Singleton {

private static Singleton instance;

private Singleton() {}

public synchronized static Singleton getInstance(){


if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Double Checked Locking
static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance == new Singleton();
}
}
return instance;
}
Lazy Holder Class
public class Singleton {

/* Static inner class */


private static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {


return SingletonHolder.INSTANCE;
}

}
Single Element Enum

public enum Singleton{


INSTANCE;
}
DON’T USE IT!

You might also like