单例模式属于创建型设计模式,确保一个类只有一个实例,并提供全局访问点。是Java中最简单但实现最复杂的设计模式。
public class EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton() {
// 防止反射攻击
if (INSTANCE != null) {
throw new IllegalStateException("Already initialized");
}
}
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
public class SynchronizedSingleton {
private static SynchronizedSingleton instance;
private SynchronizedSingleton() {}
public static synchronized SynchronizedSingleton getInstance() {
if (instance == null) {
instance = new SynchronizedSingleton();
}
return instance;
}
}
public class DCLSingleton {
private volatile static DCLSingleton instance;
private DCLSingleton() {}
public static DCLSingleton getInstance() {
if (instance == null) {
synchronized (DCLSingleton.class) {
if (instance == null) {
instance = new DCLSingleton();
}
}
}
return instance;
}
}
public class InnerClassSingleton {
private InnerClassSingleton() {}
private static class SingletonHolder {
static final InnerClassSingleton INSTANCE = new InnerClassSingleton();
}
public static InnerClassSingleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
public enum EnumSingleton {
INSTANCE;
public void doSomething() {
// 业务方法
}
}
private Singleton() {
if (instance != null) {
throw new IllegalStateException("Already initialized");
}
}
// 添加readResolve方法
protected Object readResolve() {
return getInstance();
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
实现方式 | 线程安全 | 懒加载 | 防止反射 | 防止序列化 | 性能 |
---|---|---|---|---|---|
饿汉式 | ✅ | ❌ | ❌ | ❌ | ⭐⭐⭐⭐ |
同步方法 | ✅ | ✅ | ❌ | ❌ | ⭐ |
双重检查锁 | ✅ | ✅ | ❌ | ❌ | ⭐⭐⭐ |
静态内部类 | ✅ | ✅ | ❌ | ❌ | ⭐⭐⭐⭐ |
枚举式 | ✅ | ❌ | ✅ | ✅ | ⭐⭐⭐⭐ |
Runtime类(JDK内置单例)
Runtime runtime = Runtime.getRuntime();
日志框架(LogManager)
Logger logger = LogManager.getLogManager().getLogger("");
Spring容器(ApplicationContext)
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
使用Initialization-on-demand holder
惯用法(静态内部类实现)
掌握单例模式的关键在于理解实例控制和线程安全的平衡,根据具体场景选择合适的实现方式。在分布式系统、类加载器不同的环境等特殊场景下需要特别注意单例的有效范围。