標籤:style for re c 代碼 ar new .net
傳統的double check :
public sealed class Singleton{ private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (padlock) { if (instance == null) { instance = new Singleton(); } } } return instance; } }}
缺陷:
1.代碼很臃腫
2.double check效能稍微差一些(比起後面的實現版本)
利用.net framework static特性的版本版:
public sealed class Singleton{ public static readonly Singleton instance = new Singleton(); private Singleton() { }}
1.如何保證單例和安全執行緒?
因為靜態執行個體在AppDomain裡面只有一份記憶體
2.缺陷?
靜態建構函式在field之前執行,沒有lazy(只有用的時候才執行個體)
lazy版本
public sealed class Singleton{ public static readonly Singleton instance = new Singleton(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Singleton() { } private Singleton() { }}
改進的地方:
顯示聲明靜態建構函式,告訴編譯器,在field之後執行,這樣就只有field被拿來用了,才會執行個體化