您的位置:首页 > 编程语言 > C#

C#中三种Singleton的实现方法

2011-12-31 15:57 267 查看
这个模式好像经常有人拿来谈论,我觉得理论意义比实际意义要大,所以列出三种写法,看着玩儿吧.

1. 普通写法

using System;

public class Singleton

{

private static Singleton instance;

private Singleton() {}

public static Singleton Instance

{

get

{

if (instance == null)

{

instance = new Singleton();

}

return instance;

}

}

}

优点有 1. 可以扩展, 继承个子类之类的. 2. 在需要的时候才会实例化对象. 缺点就是不是线程安全.

2. 简便写法

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
} 这种最简单直接了, 并且这也是访问的时候才会实例化. 要说劣势,那就是只能用默认的构造函数,不能加什么其他的操作.

3. 普遍实现方式

using System;

public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();

private Singleton() {}

public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
volatile 关键字很重要,多线程时候, 使用这个变量时候会重新得到实际的内存变量,就不会访问缓存中的数值.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: