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.
应用:设备驱动
单例模式详解
本文详细介绍了单例模式的三种实现方式:同步方法、急切创建实例及双重检查锁定,并探讨了每种方法的特点与适用场景。
954

被折叠的 条评论
为什么被折叠?



