轉自:http://www.techmango.com/blog/article/DotNet/Thread_Safe_Singleton_Instance.htm
許多同志都會采用一個double check的方式來創建一個Singleton:
public class Singleton
{
protected Singleton() { }
private static volatile Singleton instance = null;
/// Lazy方式創建唯一實例的過程
public static Singleton Instance()
{
if (instance == null) // 外層if
lock (typeof(Singleton)) // 多線程中共享資源同步
if (instance == null) // 內層if
instance = new Singleton();
return instance;
}
}
這應該是比較經典的線程安全的Singleton創建方式,但是還是一個更加簡單也很Cool的線程安全的Singleton:
class Singleton
{
private Singleton() { }
public static readonly Singleton Instance = new Singleton();
}
它省去了上面示例中那個laze構造過程,由于Instance是類的公共靜態成員,因此相當于它會在類第一次被用到的時候被構造,同樣的原因也就可以省去把它放在靜態構造函數里的過程。
這里實例構造函數被徹底定義為私有的,所以客戶程序和子類無法額外構造新的實例,所有的訪問通過公共靜態成員Instance獲得唯一實例的引用,符合Singleton的設計意圖。