设计模式:单件模式(singleton)
在软件系统中,经常有这样一些特殊的类,必须保证他们在系统中只存在一个实例,才能保证他们逻辑正确性,以及良好的效率.
为了使设计的类只能被实例化一次,类的设计者必须对类进行单一设计.并不是使用者只实例化一次.
Gof的设计模式:保证一个类仅有一个实例,并提供一个该实例的全局访问点.
net框架中有很多地方都使用到Singleton,比如:Type对象,HttpContext.Current

Code
1 Public class Singleton
2
3 {
4
5 Private static Singleton instance;
6
7 Private Singleton(){} //私有构造器.屏蔽系统默认的构造器
8
9 Public static Singleton Instance() //全局点
10
11 {
12
13 If(instance==null)
14
15 {
16
17 instance=new Singeton();
18
19 }
20
21 Return instance;
22
23 }
24
25 }
26
27 //或直接使用内联初始化,可以在多线程下
28
29 Public class Singleton //不支持构造传递参数,因为它的内部结构是一个静态构造器,
30
31 {
32
33 Public static readonly Singleton Instace=new Singleton();
34
35 Private Singleton(){}
36
37 //添加属性,可以给类赋值~
38
39 }
40
使用Singleton模式的几个要点:
1. Singleton模式一般不要支持ICloneable接口,因为可能导致多个对象实例.
2. Singleton模式一般不要支持序列化. 因为可能导致多个对象实例.
3. Singleton模式只考虑到了对象创建的管理,,没有考虑对像的销毁管理.就支持垃圾回收的平台和对象的开销来讲,我们一般没有必要对其销毁进行特殊的管理.
4. 不能应对多线程环境, 因为可能导致多个对象实例.如在多线程环境构建单体,需要双检查.
多线程下singleton

Code
1 Public class Singleton
2
3 {
4
5 Private static Singleton instace;
6
7 Object obj=new Object();
8
9 Public static Singleton Instace
10
11 {
12
13 Get{
14
15 If(instace==null)
16
17 {
18
19 Lock(obj)
20
21 {
22
23 If(instace==null)
24
25 {
26
27 instace=new Singleton();
28
29 }
30
31 }
32
33 }
34
35 Return instace;
36
37 }
38
39 }
40
41 }
42