January 08
C#设计模式[转]
哈哈,在搜怎么禁用那个插件的时候,顺便发现了这个,转你没商量{来源}
平时在开发中,有些模式经常使用,也叫得出名字,比如单例,简单工厂方法。但有些经常在用,却叫不出名字,部分是因为.Net Framework本身包含了很多模式,但我在使用时却常常看作了C#的语法特性,其中有些也的确是C#的语法特性,比如事件委托。
下面把这些常用的设计模式学习总结一下。
1 单例
简单的:
1 class App
2 {
3 private App(){}
4
5 private static App instance;
6
7 public static App Instance
8 {
9 get
10 {
11 if(instance == null)
12 instance = new App();
13 return instance;
14 }
15 }
16 }
线程安全的:
1 public class App
2 {
3 private static App instance;
4 private static object lockHelper = new object();
5
6 public static App Instance
7 {
8 get
9 {
10 if (instance == null)
11 {
12 lock (lockHelper)
13 {
14 if (instance == null)
15 instance = new App();
16 }
17 }
18 return instance;
19 }
20 }
21
22 private App(){}
23 }
提前初始化的:
1 class App
2 {
3 private App()
4 {
5 instance = new App();
6 }
7
8 private static App instance;
9
10 public static App Instance
11 {
12 get
13 {
14 return instance;
15 }
16 }
17 }
2 简单工厂方法
1 abstract class DBWrapper {}
2
3 class DB2Wrapper: DBWrapper {}
4 class OracleWrapper: DBWrapper {}
5
6 class Factory
7 {
8 public DBWrapper CreateInstance(int type)
9 {
10 if(type == 0)
11 return new DB2Wrapper();
12 if(type == 1)
13 return new OracleWrapper();
14
15 return null;
16 }
17 }
18
19
3 原形(Prototype)
这个就是经常使用,却不知道的模式。一个类实现.Net中的ICloneable接口后,就可以复制这个类的实例。我通常结合序列化使用。
1 class Role: IClonable
2 {
3 public string ToXml(){}
4 public void ParseXml(string xml){}
5
6 public Role Clone()
7 {
8 Role r = new Role();
9 r.ParseXml(ToXml());
10 return r;
11 }
12 }
13
4 Builder
意图是将复杂的构建和表示分离。仔细回想一下,在我的开发过程中还没有这样使用过,但有相似用法的。在最近的一个流程系统中,根据用户的请求,要创建不同的流程,这个和工厂方法有一点点相似,不同的是创建流程的过程是比较复杂的,而工厂方法只需要返回不同的对象实例即可,在创建过程中不做任何工作。
1 class FlowManager
2 {
3 Hashtable flowInstances = new Hashtable();
4
5 public Flow Create(Flow f)
6 {
7 f.Status = FlowStatus.Wait;
8 f.Handler = GetFlowHandler();
9 SendMessage(f.Handler);
10 // 
11 flowInstances.Add(f.Guid, f);
12 return f;
13 }
14 }
15
16 class Flow {}
17 enum FlowStatus { Wait, Processing, Completed }
我想这样使用恐怕算不上Builder模式,Builder模式能否在以后的开发中真正使用,得看具体的开发需要了。
5 适配器 Adapter
意图是两个程序模块之间使用的接口不兼容,这时添加一个桥接程序,分别兼容二者的接口,使两个模块能够协同工作。这就像我们在usb鼠标上接一个usb到ps2的转接线,然后把usb鼠标接到电脑的ps2接口上使用。
我在开发中还没有这样使用过。
6 Bridge
意图是将过多的继承转换为组合。.Net中的Pen和Color可以理解为使用Bridge模式。如果要将颜色也实现到Pen当中去,那需要非常多的类,将二者分开,通过组合Pen和Color,就可以实现多种多样的画笔,而不需要实现过多的子类。