Singleton Pattern: ensures a class has only one instance, and provides a global point of access to it.
Note: carefully deal with multithreading.
Synchronizing a method can decrease performance by a factor of 100.
1. Synchronize method
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
This has overhead. Lazy create. Only create instance when needed.
2. Eagerly create instance.
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return uniqueInstance;
}
}
Eager create. Create an instance even it is not used.
3. Use double-checking lockingpublic class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized(Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
This reduce the synchronize overhead. Use volatile to ensure no cached variable.
应用:设备驱动