开始看设计模式了,刚开始打算快速看完,然后再回过头来实现,但是走着发现这样不太好.
因为好多后边的模式应用到了前边的模式.前面的一知半解的话,导致后边的也知道一点.
就是什么也没有留下.
其次就是C#不太熟悉,需要实践一下.这样对看懂后来的模式会有很大的帮助.
下面说说简单工厂模式:
什么是简单工厂模式:
简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例.通俗的讲,也就是我这个公司能生产很多产品,但是具体在何种情况下生产何种产品是不知道的.必需由客户提供一个参数,也就是客户要我生产那个我就生产那个.生产的过程就是一个实例化类的过程.
简单工厂模式UML图
工厂代码:(C#),描述根据参数选择实例那种算法.
1: public class OperatonFactory
2: {
3: public static Operation createOperate(String Operate)
4: {
5: Operation oper = null;
6: switch (Operate)
7: {
8: case "+":
9: oper = new OperatonAdd();
10: break;
11: case "-":
12: oper = new OperationSub();
13: break;
14: case "*":
15: oper = new OperationMul();
16: break;
17: case "/":
18: oper = new OperationDiv();
19: break;
20: }
21: return oper;
22: }
23: }
这样在客户端.就可以利用传过来的参数,实例化对象.
1: Operation oper;
2: Console.WriteLine("选择符号+-*/");
3: oper = OperatonFactory.createOperate(Console .ReadLine ());//根据输入参数选择实例化对象
其中要实例化的类由一个抽象类和几个具体实现类组成.这样加强了代码的复用.减少了耦合.避免了添加功能时要给出原来功能的算法.体现了封装.
1: public class Operation
2: {
3: private double _numberA = 0;
4: private double _numberB = 0;
5:
6: public double NumberA
7: {
8: get { return _numberA; }
9: set { _numberA = value; }
10: }
11:
12: public double NumberB
13: {
14: get { return _numberB; }
15: set { _numberB = value; }
16:
17: }
18:
19: public virtual double GetResult()
20: {
21: double result = 0;
22: return result;
23:
24: }
25: }
26:
27: class OperatonAdd : Operation
28: {
29: public override double GetResult()
30: {
31: double result = 0;
32: result = NumberA + NumberB;
33: return result;
34: }
35: }
36:
37: class OperationSub : Operation
38: {
39: public override double GetResult()
40: {
41: double result = 0;
42: result = NumberA - NumberB;
43: return result;
44: }
45: }
46:
47: class OperationMul : Operation
48: {
49: public override double GetResult()
50: {
51: double result = 0;
52: result = NumberA * NumberB;
53: return result;
54: }
55: }
56:
57: class OperationDiv : Operation
58: {
59: public override double GetResult()
60: {
61: double result = 0;
62: if (NumberB == 0)
63: throw new Exception("除数不能为零");
64:
65: result = NumberA / NumberB;
66: return result;
67:
68: }
69: }