標籤:readonly font logs family 靜態變數 close display dad class
目的:避免對象的重複建立
單線程具體的實現代碼
/// <summary> /// 私人化建構函式 /// </summary> public class Singleton { private Singleton() {//建構函式可能耗時間,耗資源 } public static Singleton CreateInstance() { if (_Singleton == null) { _Singleton = new Singleton(); } return _Singleton; } }View Code
多線程具體的實現代碼--雙if加lock
/// <summary> /// 私人化建構函式 /// 私人靜態變數儲存對象 /// </summary> public class Singleton { private Singleton() {//建構函式可能耗時間,耗資源 } private static Singleton _Singleton = null; private static readonly object locker = new object();//加鎖 //雙if加lock public static Singleton CreateInstance() { if (_Singleton == null)//保證對象初始化之後不需要等待鎖 { lock (locker)//保證只有一個線程進去判斷 { if (_Singleton == null) { _Singleton = new Singleton(); } } } return _Singleton; } }View Code
另外的實現方法
第一種:
public class SingletonSecond { private SingletonSecond() {//建構函式可能耗時間,耗資源 } private static SingletonSecond _Singleton = null; static SingletonSecond()//靜態建構函式,由CLR保證在第一次使用時調用,而且只調用一次 { _Singleton = new SingletonSecond(); } public static SingletonSecond CreateInstance() { return _Singleton; } }View Code
第二種:
public class SingletonThird { private SingletonThird() {//建構函式可能耗時間,耗資源 } private static SingletonThird _Singleton = new SingletonThird(); public static SingletonThird CreateInstance() { return _Singleton; } }View Code
C#設計模式--單例模式