您的位置:首页 > 其它

单件模式(Singleton Pattern)

2007-09-25 20:57 239 查看
第一种:非线程安全

// Bad code! Do not use!

public sealed class Singleton

{

static Singleton instance=null;

Singleton()

{

}

public static Singleton Instance

{

get

{

if (instance==null)

{

instance = new Singleton();

}

return instance;

}

}

}
显然if(instance==null)对多线程很没有任何用处。

第二种:简单的线程安全型

public sealed class Singleton

{

static Singleton instance=null;

static readonly object padlock = new object();

Singleton()

{

}

public static Singleton Instance

{

get

{

lock (padlock)

{

if (instance==null)

{

instance = new Singleton();

}

return instance;

}

}

}

}
关键在于【locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release】

第三种:试图线程安全-利用双重检查

// Bad code! Do not use!

public sealed class Singleton

{

static Singleton instance=null;

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;

}

}

}

不妥之处:【The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance】 【Without any memory barriers, it's broken in the ECMA CLI specification too】

第四种:不算太懒,但不用lock仍可以实现线程安全

public sealed class Singleton

{

static readonly Singleton instance=new Singleton();

// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit

static Singleton()

{

}

Singleton()

{

}

public static Singleton Instance

{

get

{

return instance;

}

}

}
原因【static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced】

第五种:延迟初始化

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();

}

}

在这五种方式中,2、4相对较好,5可以实现延时初始化,也不错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: