第一種最簡單,但沒有考慮線程安全,在多線程時可能會出問題,不過俺從沒看過出錯的現象,表鄙視我……
public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
第二種考慮了線程安全,不過有點煩,但絕對是正規寫法,經典的一叉
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;
}
}
第三種可能是C#這樣的高級語言特有的,實在懶得出奇
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
哦,shit!