淺談單例的三種實現--C#
傳統的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被拿來用了,才會實例化