/// <summary>
/// 适用于单线程单例
/// </summary>
class Singleton_01
{
//将构造函数设为私有避免重复创建
//当instance为空时,实例化;
private Singleton_01()
{
}
private static Singleton_01 instance = null;
public static Singleton_01 Instance
{
get
{
if (instance == null)
instance = new Singleton_01();
return instance;
}
}
}
/// <summary>
/// 适用于多线程单例
/// 加上同步锁保证可以在多线程下工作,但是每次获取实例时,都需要加上同步锁,很耗时;
/// </summary>
class Singleton_02
{
private Singleton_02()
{
}
private static readonly object syncObj = new object();
private static Singleton_02 instance = null;
public static Singleton_02 Instance
{
get
{
lock(syncObj)
{
if (instance == null)
instance = new Singleton_02();
}
return instance;
}
}
}
/// <summary>
/// 适用于多线程单例
/// 在获取实例之前提前检测是否已经被实例化,不用多次判断,加同步锁.效率更高
/// </summary>
class Singleton_03
{
private Singleton_03()
{
}
private static readonly object syncObj = new object();
private static Singleton_03 instance = null;
public static Singleton_03 Instance
{
get
{
if (instance == null)
{
lock (syncObj)
{
if (instance == null)
instance = new Singleton_03();
}
}
return instance;
}
}
}
/// <summary>
/// 利用C#静态构造函数只执行一次的特性,实现单例
/// </summary>
class Singleton_04
{
private Singleton_04()
{
}
private static Singleton_04 instance = new Singleton_04();
public static Singleton_04 Instance
{
get
{
return instance;
}
}
}
/// <summary>
/// 按需创建实例
/// 利用C#静态类只执行一次的特性,实现单例的问题在于,只要你用到这个类,
/// 他就会创建实例,并不是在你需要的时间创建,降低了内存的使用效率,
/// 而我们创建一个内部类来实例化,在调用Instance时才会调用到instance,这样就避免了调用这个类时,自动实例化
/// </summary>
class Singleton_05
{
Singleton_05()
{
}
public static Singleton_05 Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
static Nested()
{
}
internal static readonly Singleton_05 instance = new Singleton_05();
}
}