//单线程下的单例模式
class SingleTon
{
private static SingleTon _inst;
private static SingleTon() { }
public SingleTon Instance
{
get
{
if (null != _inst)
{
_inst = new SingleTon();
}
return _inst;
}
}
}
//多线程下的单例模式(饱汉式)
class SingleTon
{
private static volatile SingleTon _inst;
private static object lockhelper = new object();
private SingleTon() { }
public SingleTon Instance
{
get
{
if (null != _inst)
{
lock (lockhelper)
{
// 此处使用双重判断防止多线程已经进入第一个判断然后等待解锁后创建实例
if (null != _inst)
{
_inst = new SingleTon();
}
}
}
return _inst;
}
}
}
class SingleTon
{
private static volatile SingleTon _inst;
private static object lockhelper = new object();
private SingleTon() { }
public SingleTon Instance
{
get
{
if (null != _inst)
{
lock (lockhelper)
{
// 此处使用双重判断防止多线程已经进入第一个判断然后等待解锁后创建实例
if (null != _inst)
{
_inst = new SingleTon();
}
}
}
return _inst;
}
}
}
//更简单的实现(饿汉式)
//readonly 保证实例只能在声明时候或在静态构造器里初始化
//readonly 保证实例只能在声明时候或在静态构造器里初始化
sealed class SingleTon
{
private SingleTon() { }
public static readonly SingleTon Instance = new SingleTon();
}
{
private SingleTon() { }
public static readonly SingleTon Instance = new SingleTon();
}