第一種最簡單,但沒有考慮線程安全,在多線程時(shí)可能會(huì)出問題
public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
第二種考慮了線程安全,不過有點(diǎn)煩,但絕對(duì)是正規(guī)寫法,經(jīng)典的一叉
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
lock(lockHelper)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
第三種,偶的最愛,因?yàn)楹唵?/span>
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}