單例模式確保類別在全域僅有一個實例,並提供全域存取點。常見應用:Spring 容器、資料庫連線池、快取管理、SessionFactory 等。本文詳細比較五種寫法的優缺點與適用場景。
newgetInstance()public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() { return INSTANCE; }
}
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
public static synchronized Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
instance 需加 volatile 防止指令重排public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() { return Holder.INSTANCE; }
}
public enum Singleton {
INSTANCE;
public void init() { System.out.println("資源初始化..."); }
}
| 方式 | 延遲載入 | 執行緒安全 | 效能 | 防反射 | 推薦場景 |
|---|---|---|---|---|---|
| 餓漢式 | 否 | 是 | 最高 | 否 | 輕量級、必定使用 |
| 懶漢式+同步 | 是 | 是 | 低 | 否 | 不推薦 |
| 雙重檢查鎖 | 是 | 是 | 高 | 否 | 需延遲載入且高併發 |
| 靜態內部類 | 是 | 是 | 高 | 否 | 通用首選 |
| 列舉 | 否 | 是 | 高 | 是 | 需防反射/序列化 |
