单例模式
单例模式是设计模式中比较简单的一种设计模式。
有许多种写法:
第一种 不考虑线程安全
/// <summary>
/// First version - not thread-safe
/// </summary>
public sealed class Singleton
{
/// <summary>
/// 静态
/// </summary>
static Singleton instance = null;
/// <summary>
/// 私有构造函数
/// </summary>
Singleton()
{ }
/// <summary>
/// public property
/// </summary>
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
第二种 线程安全
/// <summary>
/// Second version - simple thread-safety
/// </summary>
public sealed class Singleton
{
static Singleton instance = null;
/// <summary>
///
/// </summary>
static readonly object padlock = new object();
Singleton()
{ }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
第三种 我没看懂
/// <summary>
/// Third version - attempted thread-safety using double-check locking
/// </summary>
public sealed class Singleton
{
static Singleton instance = null;
/// <summary>
///
/// </summary>
static readonly object padlock = new object();
Singleton()
{ }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
return instance;
}
}
}
第四种 比较偷懒的写法
/// <summary>
/// Fourth version - not quite as lazy, but thread-safe without using locks
/// </summary>
public sealed class Singleton
{
static readonly Singleton instance = new Singleton();
/// <summary>
/// static constructor
/// </summary>
static Singleton()
{ }
public static Singleton Instance
{
get { return instance; }
}
}
第五种 比较偷懒的写法
/// <summary>
/// Fifth version - fully lazy instantiation
/// </summary>
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}