1. 静态持有者单例模式(static holder singleton pattern) html
public static class Singleton { private static class InstanceHolder { public static Singleton instance = new Singleton(); } private Singleton(){} public static Singleton getInstance() { return InstanceHolder.instance; } }
有三个好处:java
第一,静态工厂;第二,延迟初始化;第三,线程安全。安全
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; } }
参考文献code
3. 使用枚举 (Making singletons with Enum in Java)htm
public enum EnumSingleton { INSTANCE; // other methods... }