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 public virtual double GetResult() 19 { 20 double result = 0; 21 return result; 22 } 23 } 24 25 class OperationAdd : Operation 26 { 27 public override double GetResult() 28 { 29 double result = 0; 30 result = NumberA + NumberB; 31 32 return result; 33 } 34 } 35 36 class OperationSub : Operation 37 { 38 public override double GetResult() 39 { 40 double result = 0; 41 result = NumberA - NumberB; 42 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 54 return result; 55 } 56 } 57 58 class OperationDiv : Operation 59 { 60 public override double GetResult() 61 { 62 double result = 0; 63 if (Math.Abs(0 - NumberB) < 0.000001) 64 { 65 throw new Exception("除数不能为0"); 66 } 67 68 result = NumberA / NumberB; 69 70 return result; 71 } 72 }
1 public class OperationFactory 2 { 3 public static Operation createOperate(string operate) 4 { 5 Operation oper = null; 6 7 switch (operate) 8 { 9 case "+": 10 oper = new OperationAdd(); 11 break; 12 case "-": 13 oper = new OperationSub(); 14 break; 15 case "*": 16 oper = new OperationMul(); 17 break; 18 case "/": 19 oper = new OperationDiv(); 20 break; 21 } 22 23 return oper; 24 } 25 }
转自《大话设计模式》