单例模式应遵循的原则
- 私有构造方法,防止类通过常规的方法构造对象
- 已静态方法或以枚举的方式返回实例
- 在多线程的环境下,确保实例只有一个
- 在反序列化时,不会重新构造对象
一、懒汉式
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (null == instance) {
instance = new LazySingleton();
}
return instance;
}
}
二、饿汉式
public class EarlySingleton {
public static EarlySingleton instance = new EarlySingleton();
public EarlySingleton() {
}
public static EarlySingleton getInstance() {
return instance;
}
}
三、双重检测锁
public class DoubleCheckLockSingleton {
private static volatile DoubleCheckLockSingleton instance = null;
public DoubleCheckLockSingleton() {
}
public static DoubleCheckLockSingleton getInstance() {
if (null != instance) {
return instance;
}
synchronized (DoubleCheckLockSingleton.class) {
if (null == instance) {
instance = new DoubleCheckLockSingleton();
}
}
return instance;
}
}
四、CAS
public class CASSingleton {
private static final AtomicReference<CASSingleton> INSTANCE = new AtomicReference();
private CASSingleton() {
}
public static CASSingleton getInstance() {
for (; ; ) {
CASSingleton instance = INSTANCE.get();
if (null != instance) return instance;
INSTANCE.compareAndSet(null, new CASSingleton());
return INSTANCE.get();
}
}
}
五、静态内部类
public class InternalClassSingleton {
private static class InternalClassHolder {
private static InternalClassSingleton instance = new InternalClassSingleton();
}
private InternalClassSingleton() {
}
public static InternalClassSingleton getInstance() {
return InternalClassHolder.instance;
}
}
六、枚举
public enum EnumSingleton {
INSTANCE
}
七、Cache
public class CacheSingleton {
public static Map<String, String> cache = new ConcurrentHashMap<>();
}