呵呵,我本来没有C#的过多功底,只是想想像整合了书上的代码,居然OK了。
自喜一下。。
1 using System; 2 public class Operation 3 { 4 private double _numberA = 0; 5 private double _numberB = 0; 6 7 public double NumberA 8 { 9 get { return _numberA; } 10 set { _numberA = value; } 11 } 12 public double NumberB 13 { 14 get { return _numberB; } 15 set { _numberB = value; } 16 } 17 public virtual double GetResult() 18 { 19 double result = 0; 20 return result; 21 } 22 } 23 24 class OperationAdd : Operation 25 { 26 public override double GetResult() 27 { 28 double result = 0; 29 result = NumberA + NumberB; 30 return result; 31 } 32 } 33 34 class OperationSub : Operation 35 { 36 public override double GetResult() 37 { 38 double result = 0; 39 result = NumberA - NumberB; 40 return result; 41 } 42 } 43 44 class OperationMul : Operation 45 { 46 public override double GetResult() 47 { 48 double result = 0; 49 result = NumberA * NumberB; 50 return result; 51 } 52 } 53 54 class OperationDiv : Operation 55 { 56 public override double GetResult() 57 { 58 double result = 0; 59 if (NumberB == 0) 60 throw new Exception("div number can not be 0."); 61 result = NumberA / NumberB; 62 return result; 63 } 64 } 65 66 public class OperationFactory 67 { 68 public static Operation createOperate(string operate) 69 { 70 Operation oper = null; 71 switch (operate) 72 { 73 case "+": 74 oper = new OperationAdd(); 75 break; 76 case "-": 77 oper = new OperationSub(); 78 break; 79 case "*": 80 oper = new OperationMul(); 81 break; 82 case "/": 83 oper = new OperationDiv(); 84 break; 85 } 86 return oper; 87 } 88 } 89 public class OperationClient 90 { 91 class Program 92 { 93 public static void Main(string[] args) 94 { 95 Operation oper; 96 97 Console.Write("Please input numberA: "); 98 string strNumberA = Console.ReadLine(); 99 Console.Write("Please select operate(+ - * /): "); 100 string strOperate = Console.ReadLine(); 101 oper = OperationFactory.createOperate(strOperate); 102 Console.Write("Please input numberB: "); 103 string strNumberB = Console.ReadLine(); 104 oper.NumberA = Convert.ToDouble(strNumberA); 105 oper.NumberB = Convert.ToDouble(strNumberB); 106 string strResult = ""; 107 strResult = Convert.ToString(oper.GetResult()); 108 Console.WriteLine("Result is :" + strResult); 109 Console.ReadLine(); 110 Console.Write("Press any key to continue . . . "); 111 Console.ReadKey(true); 112 } 113 } 114 }
时间: 2024-11-01 00:11:46