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