单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
多线程下的单例模式:
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;
}
}
静态初始化单例:
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}