創建型模式中,單例與工廠是最高頻、最基礎的模式。本文提供 **六種單例寫法** 與 **三層工廠模式** 的完整、可運行代碼,並分析線程安全、性能、適用場景差異。
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 synchronized Singleton getInstance() { // 方法級鎖,性能差
if (instance == null) instance = new Singleton();
return instance;
}
}
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
推薦生產環境使用,兼顧延遲加載與高性能。
public class Singleton {
private Singleton() {}
private static class Holder { static final Singleton INSTANCE = new Singleton(); }
public static Singleton getInstance() { return Holder.INSTANCE; }
}
public enum Singleton { INSTANCE; }
Spring @Scope("singleton")、EJB @Singleton 等框架級單例。
public class SimpleFactory {
public static Product create(String type) {
switch (type) {
case "A": return new ProductA();
case "B": return new ProductB();
default: throw new IllegalArgumentException();
}
}
}
interface Product { void use(); }
interface Factory { Product create(); }
class ProductA implements Product { public void use() { System.out.println("A"); } }
class FactoryA implements Factory { public Product create() { return new ProductA(); } }
// 客戶端
Factory factory = new FactoryA();
Product p = factory.create(); p.use();
新增產品只需新增對應 Factory 實現,**不修改原有代碼**。
interface Product1 { void show(); }
interface Product2 { void show(); }
interface Factory { Product1 create1(); Product2 create2(); }
class FactoryImpl implements Factory {
public Product1 create1() { return new Product1Impl(); }
public Product2 create2() { return new Product2Impl(); }
}
// 客戶端
Factory f = new FactoryImpl();
f.create1().show(); f.create2().show();
適用於**一組相關/依賴對象**需一起創建的場景(如不同皮膚主題的按鈕+輸入框+窗口)。
| 模式 | 核心意圖 | 關鍵點 | 適用場景 |
|---|---|---|---|
| 單例 | 全局唯一訪問點 | 私有構造、靜態實例、靜態工廠方法 | 配置管理、連接池、緩存、日誌 |
| 簡單工廠 | 集中創建邏輯 | 靜態方法分發 | 產品固定、客戶端不關心創建細節 |
| 工廠方法 | 延遲創建到子類 | 抽象工廠介面、具體工廠實現 | 框架擴展點、插件系統 |
| 抽象工廠 | 創建產品族 | 多產品介面、工廠創建多產品 | 跨平台 UI、多数據庫適配 |
readResolve)、枚舉最強new 或簡單工廠即可掌握這些核心創建型模式,是構建可擴展、可維護 Java 系統的基石。