cly

博客园 首页 新随笔 联系 订阅 管理

Singleton

缺点:多线程情况下是不安全的

class Factory
{
private static Factory _factory;
private Factory()
{ }
public static Factory GetFactory()
{
if (_factory == null)
{
_factory
= new Factory();
}
return _factory;
}
}

静态初始化

1 //静态初始化
2   class Singleton
3 {
4 //由于构造函数是私有的,因此不能在类本身以外实例化 Singleton 类;
5   private Singleton() { }
6 //公共静态属性为访问实例提供了一个全局访问点
7   public static Singleton Instance
8 {
9 get
10 {
11 return instance;
12 }
13 }
14
15 public static Singleton GetInstance()
16 {
17 return instance;
18 }
19
20 private static readonly Singleton instance;
21 }

多线程Singleton

1 public sealed class Singleton
2 {
3 //变量被声明为 volatile,以确保只有在实例变量分配完成后才能访问实例变量。
4 private static volatile Singleton instance;
5 //此方法使用 syncRoot 实例来进行锁定(而不是锁定类型本身),以避免发生死锁。
6 private static object syncRoot = new Object();
7 private Singleton() { }
8 public static Singleton Instance
9 {
10 get
11 {
12 if (instance == null)
13 {
14 lock (syncRoot)
15 {
16 if (instance == null)
17 instance = new Singleton();
18 }
19 }
20 return instance;
21 }
22 }
23 }
posted on 2011-05-12 09:56  戒色  阅读(402)  评论(0编辑  收藏  举报