C#设计模式(7)-Singleton Pattern
http://www.cnblogs.com/zhenyulu/articles/37246.html
一、 单例(Singleton)模式
单例模式的特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其它对象提供这一实例。
单例模式应用:
- 每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。
- 一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号。否则会出现主键重复。
二、 Singleton模式的结构:
Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接实例它。除此之外,该模式中包含一个静态私有成员变量instance与静态公有方法Instance()。Instance方法负责检验并实例化自己,然后存储在静态成员变量中,以确保只有一个实例被创建。(关于线程问题以及C#所特有的Singleton将在后面详细论述)。
三、 程序举例:
该程序演示了Singleton的结构,本身不具有任何实际价值。
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
四、 在什么情形下使用单例模式:
使用Singleton模式有一个必要条件:在一个系统要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就不要使用单例模式。
注意:
不要使用单例模式存取全局变量。这违背了单例模式的用意,最好放到对应类的静态成员中。
不要将数据库连接做成单例,因为一个系统可能会与数据库有多个连接,并且在有连接池的情况下,应当尽可能及时释放连接。Singleton模式由于使用静态成员存储类实例,所以可能会造成资源无法及时释放,带来问题。
五、 Singleton模式在实际系统中的实现
下面这段Singleton代码演示了负载均衡对象。在负载均衡模型中,有多台服务器可提供服务,任务分配器随机挑选一台服务器提供服务,以确保任务均衡(实际情况比这个复杂的多)。这里,任务分配实例只能有一个,负责挑选服务器并分配任务。
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
六、 C#中的Singleton模式
C#的独特语言特性决定了C#拥有实现Singleton模式的独特方法。这里不再赘述原因,给出几个结果:
方法一:
下面是利用.NET Framework平台优势实现Singleton模式的代码:
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
这使得代码减少了许多,同时也解决了线程问题带来的性能上损失。那么它又是怎样工作的呢?
注意到,Singleton类被声明为sealed,以此保证它自己不会被继承,其次没有了Instance的方法,将原来_instance成员变量变成public readonly,并在声明时被初始化。通过这些改变,我们确实得到了Singleton的模式,原因是在JIT的处理过程中,如果类中的static属性被任何方法使用时,.NET Framework将对这个属性进行初始化,于是在初始化Instance属性的同时Singleton类实例得以创建和装载。而私有的构造函数和readonly(只读)保证了Singleton不会被再次实例化,这正是Singleton设计模式的意图。
(摘自:http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx )
不过这也带来了一些问题,比如无法继承,实例在程序一运行就被初始化,无法实现延迟初始化等。
详细情况可以参考微软MSDN文章:《Exploring the Singleton Design Pattern》
方法二:
既然方法一存在问题,我们还有其它办法。
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
这实现了延迟初始化,并具有很多优势,当然也存在一些缺点。详细内容请访问:《Implementing the Singleton Pattern in C#》。文章包含五种Singleton实现,就模式、线程、效率、延迟初始化等很多方面进行了详细论述。
参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社
.NET设计模式(2):单件模式(Singleton Pattern)
http://terrylee.cnblogs.com/archive/2005/12/09/293509.html单件模式(Singleton Pattern)
——.NET设计模式系列之二
Terrylee,2005年12月07日
概述
Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点。这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程序在调用某一个类时,它是不会考虑这个类是否只能有一个实例等问题的,所以,这应该是类设计者的责任,而不是类使用者的责任。
从另一个角度来说,Singleton模式其实也是一种职责型模式。因为我们创建了一个对象,这个对象扮演了独一无二的角色,在这个单独的对象实例中,它集中了它所属类的所有权力,同时它也肩负了行使这种权力的职责!
意图
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
模型图
逻辑模型图:
物理模型图:
生活中的例子
美国总统的职位是Singleton,美国宪法规定了总统的选举,任期以及继任的顺序。这样,在任何时刻只能由一个现任的总统。无论现任总统的身份为何,其头衔"美利坚合众国总统"是访问这个职位的人的一个全局的访问点。
五种实现
1.简单实现
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
这种方式的实现对于线程来说并不是安全的,因为在多线程的环境下有可能得到Singleton类的多个实例。如果同时有两个线程去判断(instance == null),并且得到的结果为真,这时两个线程都会创建类Singleton的实例,这样就违背了Singleton模式的原则。实际上在上述代码中,有可能在计算出表达式的值之前,对象实例已经被创建,但是内存模型并不能保证对象实例在第二个线程创建之前被发现。
该实现方式主要有两个优点:
l 由于实例是在 Instance 属性方法内部创建的,因此类可以使用附加功能(例如,对子类进行实例化),即使它可能引入不想要的依赖性。
l 直到对象要求产生一个实例才执行实例化;这种方法称为“惰性实例化”。惰性实例化避免了在应用程序启动时实例化不必要的 singleton。
2.安全的线程
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
25
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
26
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
这种方式的实现对于线程来说是安全的。我们首先创建了一个进程辅助对象,线程在进入时先对辅助对象加锁然后再检测对象是否被创建,这样可以确保只有一个实例被创建,因为在同一个时刻加了锁的那部分程序只有一个线程可以进入。这种情况下,对象实例由最先进入的那个线程创建,后来的线程在进入时(instence == null)为假,不会再去创建对象实例了。但是这种实现方式增加了额外的开销,损失了性能。
3.双重锁定
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
25
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
26
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
27
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
28
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
这种实现方式对多线程来说是安全的,同时线程不是每次都加锁,只有判断对象实例没有被创建时它才加锁,有了我们上面第一部分的里面的分析,我们知道,加锁后还得再进行对象是否已被创建的判断。它解决了线程并发问题,同时避免在每个Instance 属性方法的调用中都出现独占锁定。它还允许您将实例化延迟到第一次访问对象时发生。实际上,应用程序很少需要这种类型的实现。大多数情况下我们会用静态初始化。这种方式仍然有很多缺点:无法实现延迟初始化。
4.静态初始化
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
看到上面这段富有戏剧性的代码,我们可能会产生怀疑,这还是Singleton模式吗?在此实现中,将在第一次引用类的任何成员时创建实例。公共语言运行库负责处理变量初始化。该类标记为sealed以阻止发生派生,而派生可能会增加实例。此外,变量标记为 readonly,这意味着只能在静态初始化期间(此处显示的示例)或在类构造函数中分配变量。
该实现与前面的示例类似,不同之处在于它依赖公共语言运行库来初始化变量。它仍然可以用来解决 Singleton 模式试图解决的两个基本问题:全局访问和实例化控制。公共静态属性为访问实例提供了一个全局访问点。此外,由于构造函数是私有的,因此不能在类本身以外实例化Singleton类;因此,变量引用的是可以在系统中存在的唯一的实例。
由于 Singleton 实例被私有静态成员变量引用,因此在类首次被对Instance 属性的调用所引用之前,不会发生实例化。
这种方法唯一的潜在缺点是,您对实例化机制的控制权较少。在 Design Patterns形式中,您能够在实例化之前使用非默认的构造函数或执行其他任务。由于在此解决方案中由.NET Framework负责执行初始化,因此您没有这些选项。在大多数情况下,静态初始化是在 .NET中实现Singleton 的首选方法。
5.延迟初始化
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
这里,初始化工作有Nested类的一个静态成员来完成,这样就实现了延迟初始化,并具有很多的优势,是值得推荐的一种实
现方式。
实现要点
l Singleton模式是限制而不是改进类的创建。
l Singleton类中的实例构造器可以设置为Protected以允许子类派生。
l Singleton模式一般不要支持Icloneable接口,因为这可能导致多个对象实例,与Singleton模式的初衷违背。
l Singleton模式一般不要支持序列化,这也有可能导致多个对象实例,这也与Singleton模式的初衷违背。
l Singleton只考虑了对象创建的管理,没有考虑到销毁的管理,就支持垃圾回收的平台和对象的开销来讲,我们一般没必要对其销毁进行特殊的管理。
l 理解和扩展Singleton模式的核心是“如何控制用户使用new对一个类的构造器的任意调用”。
l 可以很简单的修改一个Singleton,使它有少数几个实例,这样做是允许的而且是有意义的。
优点
l 实例控制:Singleton会阻止其他对象实例化其自己的Singleton 对象的副本,从而确保所有对象都访问唯一实例
l 灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程
缺点
l 开销:虽然数量很少,但如果每次对象请求引用时都要检查是否存在类的实例,将仍然需要一些开销。可以通过使用静态初始化解决此问题,上面的五种实现方式中已经说过了。
l 可能的开发混淆:使用singleton对象(尤其在类库中定义的对象)时,开发人员必须记住自己不能使用 new关键字实例化对象。因为可能无法访问库源代码,因此应用程序开发人员可能会意外发现自己无法直接实例化此类。
l 对象的生存期:Singleton不能解决删除单个对象的问题。在提供内存管理的语言中(例如基于 .NET Framework的语言),只有Singleton 类能够导致实例被取消分配,因为它包含对该实例的私有引用。在某些语言中(如 C++),其他类可以删除
对象实例,但这样会导致 Singleton 类中出现悬浮引用。
适用性
l 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
l 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。
应用场景
l 每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。
(摘自吕震宇的C#设计模式(7)-Singleton Pattern)
l PC机中可能有几个串口,但只能有一个COM1口的实例。
l 系统中只能有一个窗口管理器。
l .NET Remoting中服务器激活对象中的Sigleton对象,确保所有的客户程序的请求都只有一个实例来处理。
完整示例
这是一个简单的计数器例子,四个线程同时进行计数。
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
25
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
26
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
27
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
28
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
29
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
30
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
31
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
32
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
33
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
34
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
35
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
36
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
37
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
38
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
39
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
40
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
41
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
42
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
43
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
44
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
45
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
46
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
47
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
48
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
25
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
26
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
27
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
28
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
29
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
30
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
31
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
32
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
33
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
34
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
35
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
36
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
37
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
38
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
39
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
40
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
41
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
42
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
43
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
44
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
45
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
46
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
47
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
48
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
49
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
50
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
51
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
52
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
53
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
54
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
55
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
56
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
57
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
58
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
59
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
60
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
61
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
62
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
63
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
64
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
65
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
66
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
67
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
68
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
69
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
70
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
71
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
72
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
73
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
74
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
75
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
76
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
77
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
78
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
79
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
7
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
8
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
9
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
12
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
14
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
15
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
16
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
17
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
19
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
20
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
21
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
22
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
23
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
24
![](http://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
总结
Singleton设计模式是一个非常有用的机制,可用于在面向对象的应用程序中提供单个访问点。文中通过五种实现方式的比较和一个完整的示例,完成了对Singleton模式的一个总结和探索。用一句广告词来概括Singleton模式就是“简约而不简单”。
_________________________________________________________________________________________________
源码下载:/Files/Terrylee/SigletonPattern.rar
参考文献:
《C#计模式》,中国电力出版社
使用 Microsoft .NET 的企业解决方案模式
《Implementing the Singleton Pattern in C#》
MSDN《Exploring the Singleton Design Pattern》
吕震宇C#设计模式(7)-Singleton Pattern
C#的Singleton设计模式
出处: http://terrylee.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
设计模式4:Singleton Pattern (单例模式)
原文:http://www.cnblogs.com/zhenyulu/articles/37246.html
参考于:http://www.dofactory.com/Patterns/PatternSingleton.aspx
一、 单例(Singleton)模式
单例模式的特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其它对象提供这一实例。
单例模式应用:
- 每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。
- 一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号。否则会出现主键重复。
二、 Singleton模式的结构:
Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接实例它。除此之外,该模式中包含一个静态私有成员变量instance与静态公有方法Instance()。Instance方法负责检验并实例化自己,然后存储在静态成员变量中,以确保只有一个实例被创建。(关于线程问题以及C#所特有的Singleton将在后面详细论述)。
三、 程序举例:
该程序演示了Singleton的结构,本身不具有任何实际价值。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Single_Pattern
- {
- // Singleton pattern -- Structural example
- // "Singleton"
- class Singleton
- {
- // Fields
- private static Singleton instance;
- // Constructor
- protected Singleton() {}
- // Methods
- public static Singleton Instance()
- {
- // Uses "Lazy initialization"
- if( instance == null )
- instance = new Singleton();
- return instance;
- }
- }
- /**//// <summary>
- /// Client test
- /// </summary>
-
- public class Client
- {
- public static void Main()
- {
- // Constructor is protected -- cannot use new
- Singleton s1 = Singleton.Instance();
- Singleton s2 = Singleton.Instance();
- if( s1 == s2 )
- Console.WriteLine( "The same instance" );
- Console.Read();
- }
- }
- }
四、 在什么情形下使用单例模式:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Single_Pattern
- {
- // Singleton pattern -- Structural example
- // "Singleton"
- class Singleton
- {
- // Fields
- private static Singleton instance;
- // Constructor
- protected Singleton() {}
- // Methods
- public static Singleton Instance()
- {
- // Uses "Lazy initialization"
- if( instance == null )
- instance = new Singleton();
- return instance;
- }
- }
- /**//// <summary>
- /// Client test
- /// </summary>
- public class Client
- {
- public static void Main()
- {
- // Constructor is protected -- cannot use new
- Singleton s1 = Singleton.Instance();
- Singleton s2 = Singleton.Instance();
- if( s1 == s2 )
- Console.WriteLine( "The same instance" );
- Console.Read();
- }
- }
- }
使用Singleton模式有一个必要条件:在一个系统要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就不要使用单例模式。
注意:
不要使用单例模式存取全局变量。这违背了单例模式的用意,最好放到对应类的静态成员中。
不要将数据库连接做成单例,因为一个系统可能会与数据库有多个连接,并且在有连接池的情况下,应当尽可能及时释放连接。Singleton模式由于使用静态成员存储类实例,所以可能会造成资源无法及时释放,带来问题。
五、 Singleton模式在实际系统中的实现
下面这段Singleton代码演示了负载均衡对象。在负载均衡模型中,有多台服务器可提供服务,任务分配器随机挑选一台服务器提供服务,以确保任务均衡(实际情况比这个复杂的多)。这里,任务分配实例只能有一个,负责挑选服务器并分配任务。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Collections;
-
- namespace Single_Pattern
- {
- // "Singleton"
- class LoadBalancer
- {
- // Fields
- private static LoadBalancer balancer;
- private ArrayList servers = new ArrayList();
- private Random random = new Random();
-
- // Constructors (protected)
- protected LoadBalancer()
- {
-
- // List of available servers
- servers.Add( "ServerI" );
- servers.Add( "ServerII" );
- servers.Add( "ServerIII" );
- servers.Add( "ServerIV" );
- servers.Add( "ServerV" );
- }
-
- // Methods
- public static LoadBalancer GetLoadBalancer()
- {
- // Support multithreaded applications through
- // "Double checked locking" pattern which avoids
- // locking every time the method is invoked
- if( balancer == null )
- {
- // Only one thread can obtain a mutex
- Mutex mutex = new Mutex();
- mutex.WaitOne();
- if( balancer == null )
- balancer = new LoadBalancer();
- mutex.Close();
- }
- return balancer;
- }
- // Properties
- public string Server
- {
- get
- {
- // Simple, but effective random load balancer
- int r = random.Next( servers.Count );
- return servers[ r ].ToString();
- }
- }
- }
-
-
- /**//// <summary>
- /// SingletonApp test
- /// </summary>
- ///
-
- public class SingletonApp
- {
- public static void Main( string[] args )
- {
- LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
-
- // Same instance?
- if( (b1 == b2) && (b2 == b3) && (b3 == b4) )
- Console.WriteLine( "Same instance" );
- // Do the load balancing
- Console.WriteLine( b1.Server );
- Console.WriteLine( b2.Server );
- Console.WriteLine( b3.Server );
- Console.WriteLine( b4.Server );
- Console.Read();
- }
- }
- }
六、 C#中的Singleton模式
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Collections;
- namespace Single_Pattern
- {
- // "Singleton"
- class LoadBalancer
- {
- // Fields
- private static LoadBalancer balancer;
- private ArrayList servers = new ArrayList();
- private Random random = new Random();
- // Constructors (protected)
- protected LoadBalancer()
- {
- // List of available servers
- servers.Add( "ServerI" );
- servers.Add( "ServerII" );
- servers.Add( "ServerIII" );
- servers.Add( "ServerIV" );
- servers.Add( "ServerV" );
- }
- // Methods
- public static LoadBalancer GetLoadBalancer()
- {
- // Support multithreaded applications through
- // "Double checked locking" pattern which avoids
- // locking every time the method is invoked
- if( balancer == null )
- {
- // Only one thread can obtain a mutex
- Mutex mutex = new Mutex();
- mutex.WaitOne();
- if( balancer == null )
- balancer = new LoadBalancer();
- mutex.Close();
- }
- return balancer;
- }
- // Properties
- public string Server
- {
- get
- {
- // Simple, but effective random load balancer
- int r = random.Next( servers.Count );
- return servers[ r ].ToString();
- }
- }
- }
- /**//// <summary>
- /// SingletonApp test
- /// </summary>
- ///
- public class SingletonApp
- {
- public static void Main( string[] args )
- {
- LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
- // Same instance?
- if( (b1 == b2) && (b2 == b3) && (b3 == b4) )
- Console.WriteLine( "Same instance" );
- // Do the load balancing
- Console.WriteLine( b1.Server );
- Console.WriteLine( b2.Server );
- Console.WriteLine( b3.Server );
- Console.WriteLine( b4.Server );
- Console.Read();
- }
- }
- }
C#的独特语言特性决定了C#拥有实现Singleton模式的独特方法。这里不再赘述原因,给出几个结果:
方法一:
下面是利用.NET Framework平台优势实现Singleton模式的代码:
- sealed class Singleton
- {
- private Singleton();
- public static readonly Singleton Instance=new Singleton();
- }
这使得代码减少了许多,同时也解决了线程问题带来的性能上损失。那么它又是怎样工作的呢?
注意到,Singleton类被声明为sealed,以此保证它自己不会被继承,其次没有了Instance的方法,将原来_instance成员变量变成public readonly,并在声明时被初始化。通过这些改变,我们确实得到了Singleton的模式,原因是在JIT的处理过程中,如果类中的static属性被任何方法使用时,.NET Framework将对这个属性进行初始化,于是在初始化Instance属性的同时Singleton类实例得以创建和装载。而私有的构造函数和readonly(只读)保证了Singleton不会被再次实例化,这正是Singleton设计模式的意图。
(摘自:http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx )
不过这也带来了一些问题,比如无法继承,实例在程序一运行就被初始化,无法实现延迟初始化等。
详细情况可以参考微软MSDN文章:《Exploring the Singleton Design Pattern》
方法二:
既然方法一存在问题,我们还有其它办法。
- public sealed class Singleton
- {
- Singleton()
- {
- }
- public static Singleton GetInstance()
- {
- 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();
- }
- }
这实现了延迟初始化,并具有很多优势,当然也存在一些缺点。详细内容请访问:《Implementing the Singleton Pattern in C#》。文章包含五种Singleton实现,就模式、线程、效率、延迟初始化等很多方面进行了详细论述。
乐在其中设计模式(C#) - 单例模式(Singleton Pattern)
在其中设计模式(C#) - 单例模式(Singleton Pattern)作者: webabcd
介绍
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
示例
保证一个类仅有一个实例。
![](https://i-blog.csdnimg.cn/blog_migrate/02e7300cf8c2ef2779fadfb5dc680f95.png)
Singleton
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
Test
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/587e34b10dcf5efbc0859b53470a2db3.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/3112b7b6526db5bc83e275260ae60525.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/eec4c0236afc26744c9c4e910bc34958.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4fd96b3cf02f4c7b5c8964ac8167f7af.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
运行结果
2007-2-10 22:35:11
2007-2-10 22:35:11
2007-2-10 22:35:14
2007-2-10 22:35:17
参考
http://www.dofactory.com/Patterns/PatternSingleton.aspx
OK
[源码下载]
http://www.yoda.arachsys.com/csharp/singleton.html
This article is now hosted on csharpindepth.com
I'm gradually moving all my C# articles to the web site for my book, C# in Depth. This article has already moved. I'm leaving the content here so that existing links still work, but I won't be updating this page.
Please visit the new location for this article.
Implementing the Singleton Pattern in C#
The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.
There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private
modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private
should be used.
All these implementations share four common characteristics, however:
- A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern).Note that it also prevents subclassing - if a singleton can be subclassed once, it can besubclassed twice, and if each of those subclasses can create an instance, the pattern isviolated. The factory pattern can be used if you need a single instance of a base type,but the exact type isn't known until runtime.
- The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
- A static variable which holds a reference to the single created instance, if any.
- A public static means of getting the reference to the single created instance, creatingone if necessary.
Note that all of these implementations also use a public static property Instance
as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.
First version - not thread-safe
// 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; } } } |
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null)
and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.
Second version - simple thread-safety
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; } } } } |
This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as 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) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton)
as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.
Third version - attempted thread-safety using double-check locking
// 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; } } } |
This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:
- It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowingif you ever need the singleton pattern in Java, and C# programmers may well also be Javaprogrammers. The Java memory model doesn't ensure that the constructor completes beforethe reference to the new object is assigned to instance. The Java memory model underwenta reworking for version 1.5, but double-check locking is still broken after this without a volatilevariable (as in C#).
- Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the
instance
variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong! - It's easy to get wrong. The pattern needs to be pretty much exactly as above - anysignificant changes are likely to impact either performance or correctness.
- It still doesn't perform as well as the later implementations.
Fourth version - not quite as lazy, but thread-safe without using locks
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; } } } |
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
- It's not as lazy as the other implementations. In particular, if you have static members other than
Instance
, the first reference to those members will involve creating the instance. This is corrected in the next implementation. - There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
- The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called
beforefieldinit
. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) asbeforefieldinit
. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.
One shortcut you can take with this implementation (and only this one) is to just make instance
a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)
Fifth version - fully lazy instantiation
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(); } } |
Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance
. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance
to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.
Performance vs laziness
In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)
Exceptions
Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.
Thanks to Andriy Tereshchenko for raising this issue.
A word on performance
A lot of the reason for this page stemmed from people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I've written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It's not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.
I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.
Conclusion (modified slightly on January 7th 2006)
There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a few very particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don't personally see that situation coming up often enough to merit going further with on this page, but please mail me if you're in that situation.
My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.
Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful.
(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no benefits over 5.)
http://csharpindepth.com/Articles/General/Singleton.aspx
Implementing the Singleton Pattern in C#
The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.
There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.
All these implementations share four common characteristics, however:
- A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
- The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
- A static variable which holds a reference to the single created instance, if any.
- A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance
as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.
First version - not thread-safe
public sealed class Singleton
{
private static Singleton instance= null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance== null)
{
instance = new Singleton();
}
return instance;
}
}
}
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null)
and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.
Second version - simple thread-safety
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as 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) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton)
as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.
Third version - attempted thread-safety using double-check locking
public sealed class Singleton
{
private static Singleton instance = null;
private 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;
}
}
}
This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:
- It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
- Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the
instance
variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong! - It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
- It still doesn't perform as well as the later implementations.
Fourth version - not quite as lazy, but thread-safe without using locks
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
- It's not as lazy as the other implementations. In particular, if you have static members other than
Instance
, the first reference to those members will involve creating the instance. This is corrected in the next implementation. - There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
- The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called
beforefieldinit
. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) asbeforefieldinit
. I now have an article with more details about this issue. Also note that it affects performance, as discussed near the bottom of the page.
One shortcut you can take with this implementation (and only this one) is to just make instance
a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)
Fifth version - fully lazy instantiation
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance
. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance
to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.
Sixth version - using .NET 4's Lazy<T>
type
If you're using .NET 4 (or higher), you can use the System.Lazy<T> type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
Performance vs laziness
In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)
Exceptions
Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.
Thanks to Andriy Tereshchenko for raising this issue.
A word on performance
A lot of the reason for this page stemmed from people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I've written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It's not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. (Note: this article was originally written quite a while ago now - I'd expect better performance now.) That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.
I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.
Conclusion (modified slightly on January 7th 2006; updated Feb 12th 2011)
There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a few very particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don't personally see that situation coming up often enough to merit going further with on this page, but please mail me if you're in that situation.
My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.
Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful. Solution 6 is a simpler way to achieve laziness, if you're using .NET 4. It also has the advantage that it's obviously lazy. I currently tend to still use solution 4, simply through habit - but if I were working with inexperienced developers I'd quite possibly go for solution 6 to start with as an easy and universally applicable pattern.
(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no benefits over 5.)