单例模式的三种实现方法

第一种、双锁定法 

public sealed class Singleton
{
static Singleton instance = null;
static readonly object lockhelper = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockhelper)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

 

第二种、静态初始化

public sealed class Singleton
{
static readonly Singleton instance = new Singleton();

static Singleton()
{
}

Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

 

第三种、延时初始化

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

 

posted @ 2012-03-04 20:55  zeus2  Views(293)  Comments(0Edit  收藏  举报