浅浅一谈 设计模式
看软件设计资料,走到设计模式这里,一头雾水。遂翻书学习,这里简单记录一下,为以后复习用
1,简单工厂
简单工厂 写一个计算 加减乘除的运算
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 SampleFactory factory = new SampleFactory(); 6 OperationClass operationclass = factory.CreateOpreation('/'); 7 //找到要操作的类了 8 //对类进行初始化 9 operationclass.FirstNum = 1; 10 operationclass.SecondeNum = 3; 11 12 //调用函数 进行计算 13 double result= operationclass.GetResult(); 14 15 Console.Write(result.ToString()); 16 Console.Read(); 17 } 18 } 19 20 /// <summary> 21 /// 运算类 22 /// </summary> 23 class OperationClass 24 { 25 private double firstNum; 26 27 public double FirstNum 28 { 29 get { return firstNum; } 30 set { firstNum = value; } 31 } 32 private double secondeNum; 33 34 public double SecondeNum 35 { 36 get { return secondeNum; } 37 set { secondeNum = value; } 38 } 39 40 private double result; 41 public virtual double GetResult() 42 { 43 result = 0; 44 return result; 45 } 46 47 } 48 49 50 class Add :OperationClass 51 { 52 public override double GetResult() 53 { 54 return FirstNum + SecondeNum; 55 } 56 } 57 58 class Sub : OperationClass 59 { 60 public override double GetResult() 61 { 62 return FirstNum - SecondeNum; 63 } 64 } 65 66 class Chu : OperationClass 67 { 68 public override double GetResult() 69 { 70 return FirstNum / SecondeNum; 71 } 72 } 73 /// <summary> 74 /// 简单工厂 75 /// </summary> 76 class SampleFactory 77 { 78 public OperationClass CreateOpreation(char c) 79 { 80 OperationClass operationclass;//运算类 基类 81 switch (c) 82 { 83 case '+': 84 operationclass = new Add(); 85 break; 86 case '-': 87 operationclass=new Sub(); 88 break; 89 case '/': 90 operationclass = new Chu (); 91 break; 92 default: 93 operationclass =null; 94 break; 95 } 96 return operationclass; 97 } 98 }
在功能变动时
优点:客户端不用改代码
缺点:当需要增加新的运算类的时候,不仅需新加运算类,还要修改工厂类,违反了开闭原则。
2.工厂方法模式