Design Pattern: Factory
reading note
The used examples and notions almost come from OOD Design.
/*
Because keyword synchronized is very expensive when talking about the performance, we could make a waste after the instance is instantiated.
*/
class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
//Lazy instantiation using double locking mechanism
class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton()
}
}
}
return instance;
}
}
//Early instantiation using implementation with static field. The class is loaded once so it can guarantee the uniquity of the object
class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return instance;
}
}
/*
Serialization
if a Singeton class implements the java.io.Serializable interface, when the singeton is serialized and then deserialized more than once, there will be multiple instances of the Singleton class created. In order to prevent this the readResolve method should be implemented.
*/
public class Singleton implements Serializable {
/*
This method is called immediately after an object of this class is deserialized.
*/
protected Object readResolve() {
return get Instance();
}
}