一、單例模式的定義
確保一個類只有一個實例,並提供一個全局訪問點來訪問這個唯一的實例,是一種對象創建型模式,有如下3個要點:
- 只能有一個實例
- 必須是自行創建這個實例
- 必須自行向整個系統提供這個實例
二、單例模式的結構
- 一個類型為自身的靜態私有成員變量 - 存儲唯一實例
- 一個私有的構造函數
- 一個公有的靜態成員方法 ,返回唯一實例,對象為自身
1 class SingletonClass 2 { 3 private static SingletonClass _instance = null; //靜態私有成員變量,存儲唯一實例 4 5 private SingletonClass() //私有構造函數,保證唯一性 6 { 7 } 8 9 public static SingletonClass GetInstance() //公有靜態方法,返回一個唯一的實例 10 { 11 if (_instance == null) 12 { 13 _instance = new SingletonClass(); 14 } 15 return _instance; 16 } 17 }
三、單例模式的兩種書寫方法
1.類被加載時就將自己實例化

1 class SingletonClass 2 { 3 private static SingletonClass _instance = new SingletonClass(); 4 5 private SingletonClass() 6 { 7 } 8 9 public static SingletonClass GetInstance() 10 { 11 return _instance; 12 } 13 }
2.類在第一次被引用時將自己實例化

1 class SingletonClass 2 { 3 private static SingletonClass _instance = null; 4 private static readonly object syncRoot = new object(); 5 6 private SingletonClass() 7 { 8 } 9 10 public static SingletonClass GetInstance() 11 { 12 if (_instance == null) 13 { 14 lock (syncRoot) 15 { 16 if (_instance == null) 17 { 18 _instance = new SingletonClass(); 19 } 20 } 21 } 22 return _instance; 23 } 24 }
四、雙重鎖的運用分析
在上述代碼中出現“If - Lock - If”結構模式,即雙重檢查鎖定的雙重判斷機制:
1 if (_instance == null) //第一重判斷,先判斷實例是否存在,不存在再加鎖處理 2 { 3 lock (syncRoot) //加鎖,在某一時刻只允許一個線程訪問 4 { 5 if (_instance == null) //第二重判斷: 第一個線程進入Lock中執行創建代碼,第二個線程處於排隊等待狀態,當第二個線程進入Lock后並不知道實例已創建,將會繼續創建新的實例 6 { 7 _instance = new SingletonClass(); 8 } 9 } 10 }
五、單例模式的優缺點
- 封裝了唯一性,可嚴格控制客戶怎么訪問及何時訪問
- 內存中只存在一個對象,可節約系統資源,提高系統性能
- 單例類的擴展不方便
- 單例類既提供了業務方法,又提供了創建對象的方法,將對象的創建和對象本身的功能耦合在一起
六、適用環境
系統只需要一個實例對象,客戶調用類的單個實例只允許使用一個公共訪問點,除了公共訪問點,不能通過其他途徑訪問該實例