一、單例模式核心價值與實現原則
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