你好!以下是标准的Singleton pattern with Double-check lock。
public class SingletonClass
{
private static readonly object _lock = new object();
private static volatile SingletonClass _instance;
public static SingletonClass Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new SingletonClass();
}
}
}
return _instance;
}
}
private SingletonClass()
{
//your constructor
}
}
如果你的.NET在4.0以上,可以借助Lazy
public class LazySingleton
{
private static readonly Lazy_instance = new Lazy (() => new LazySingleton());
private LazySingleton()
{
//your constructor
}
public static LazySingleton Instance { get { return _instance.Value; } }
}