1. 静态持有者单例模式(static holder singleton pattern)
public static class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
private Singleton(){}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
}
有三个好处:
第一,静态工厂;第二,延迟初始化;第三,线程安全。
2. 双重检查锁(singleton with double checked locking)
public class Singleton {
private Singleton(){
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) { // Single checked
synchronized (Singleton.class) {
if (instance == null) { // Double checked
instance = new Singleton();
}
}
}
return instance;
}
}
3. 使用枚举 (Making singletons with Enum in Java)
public enum EnumSingleton {
INSTANCE;
// other methods...
}