singleton sum
DESCRIPTION
Summarise singleton pattern : lazy and eager designTRANSCRIPT
Singleton Singleton pattern in java enterprise world
Slim Ouertani
Intent
Ensure a class only has one instance, and provide a global point of access to it. [GoF p 119]
Motivation
It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler.
How do we ensure that a class has only one instance and that the instance is easily accessible?
A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.
Motivation
A better solution is to make the class itself responsible for keeping track of its sole instance.
The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance.
This is the Singleton pattern.
HOW ?
Before release 1.5, there were two ways to implement singletons.
Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance.
In one approach, the member is a final field
Singleton with public final field
public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public void leaveTheBuilding() { ... }}
Reflexion!!!
Singleton with static factory
public class Elvis implements Serializable{
private static final Elvis INSTANCE = new Elvis();
private Elvis() {}
public static Elvis getInstance() {
return INSTANCE;
}
}
Serialisation!!!
singleelement enum type
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
JAVA 5
Lazy initialization
Lazy initialization is the act of delaying the initialization of a field until its value is needed.
If the value is never needed, the field is never initialized.
Lazy initialization is a doubleedged sword. It decreases the cost of initializing a class or creating an instance, at the expense of increasing the cost of accessing the lazily initialized field.
In the presence of multiple threads, lazy initialization is tricky.
Lazy initialization of instance fieldsynchronized accessor
private static Elvis elvis;synchronized static Elvis getElvis() { if (elvis == null) elvis = new Elvis(); return elvis;}
Slow!!!
DoubleChecked Locking idiomDCL
static volatile Singleton instance;public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance == new Singleton(); } } return instance;}
No java 1.4!!!
Lazy initialization holder class idiom
private static class ElvisHolder { static final Elvis INSTANCE = new Elvis();}static Elvis getInstance() {
return ElvisHolder.INSTANCE; }
JAVA 5 & 1.4
References
GoF
Effective Java 1 & 2
http://fr.wikipedia.org/wiki/Doublechecked_locking