首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 單例模式深度解析:五種實作方式與優缺點比較

     編輯:Java 相關知識

模式定義與應用場景

單例模式確保某個類別在整個系統中僅有一個實例,並自行實例化且提供全域存取點。適用於建立物件資源消耗大、需頻繁建立銷毀、或需共享資源(如資料庫連線、執行緒池、配置管理)的場景。

UML 類別圖

包含兩個角色:Client(高層客戶端)與 Singleton(單例類別)。Singleton 提供私有建構子、靜態實例變數與公開的 getInstance() 方法。

五種經典實作方式

1. 雙重檢查鎖定 - 線程安全、延遲載入

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;
    }
}

2. 餓漢式 - 類別載入時即建立實例

public class Singleton1 {
    private static final Singleton1 INSTANCE = new Singleton1();
    private Singleton1() {}
    public static Singleton1 getInstance() { return INSTANCE; }
}

3. 懶漢式(非線程安全)

public class Singleton2 {
    private static Singleton2 instance;
    private Singleton2() {}
    public static Singleton2 getInstance() {
        if (instance == null) instance = new Singleton2();
        return instance;
    }
}

4. 懶漢式同步方法 - 線程安全但效能較低

public class Singleton3 {
    private static Singleton3 instance;
    private Singleton3() {}
    public synchronized static Singleton3 getInstance() {
        if (instance == null) instance = new Singleton3();
        return instance;
    }
}

5. 懶漢式同步區塊 - 效能略優於同步方法

public class Singleton4 {
    private static Singleton4 instance;
    private Singleton4() {}
    public static Singleton4 getInstance() {
        synchronized (Singleton4.class) {
            if (instance == null) instance = new Singleton4();
        }
        return instance;
    }
}

優缺點總結

優點

  • 減少記憶體開銷,避免頻繁建立銷毀物件。
  • 系統啟動時預先建立實例,常駐記憶體,提升存取效能。
  • 避免對共享資源(如檔案寫入)的多重佔用衝突。
  • 提供全域存取點,便於資源共享與管理。

缺點

  • 通常不實作介面,擴充困難,修改需動原始碼。
  • 若單例持有過多狀態,可能違反單一職責原則。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved