一、单例模式核心价值与实现原则
1. 使用场景
- 全局配置类(如数据库连接池)
- 日志记录器
- Spring默认Bean作用域
- 硬件设备访问(如打印机)
2. 设计三原则
- 私有构造器:禁止外部实例化
- 静态实例持有:全局唯一访问点
- 延迟加载(可选):避免资源浪费
二、七种单例实现方式深度解析
1. 饿汉式(急加载)
public class EagerSingleton { private static final EagerSingleton INSTANCE = new EagerSingleton(); private EagerSingleton() {} public static EagerSingleton getInstance() { return INSTANCE; }
}
优点:线程安全、实现简单
缺点:类加载即初始化,可能浪费资源
2. 懒汉式(基础版 - 非线程安全)
public class LazySingleton { private static LazySingleton instance; private LazySingleton() {} public static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; }
}
风险:多线程环境下可能创建多个实例
3. 同步锁懒汉式(线程安全版)
public class SyncLazySingleton { private static SyncLazySingleton instance; private SyncLazySingleton() {} public static synchronized SyncLazySingleton getInstance