设计模式之☞简单工厂模式
程序员文章站
2022-04-24 21:58:04
通过多态制作一个简单的计算器 Operation类: 1 public class Operation 2 { 3 private double _numberA = 0; 4 private double _numberB = 0; 5 public double NumberA 6 { 7 ge ......
通过多态制作一个简单的计算器
operation类:
1 public class operation 2 { 3 private double _numbera = 0; 4 private double _numberb = 0; 5 public double numbera 6 { 7 get 8 { 9 return _numbera; 10 } 11 12 set 13 { 14 _numbera = value; 15 } 16 } 17 public double numberb 18 { 19 get 20 { 21 return _numberb; 22 } 23 24 set 25 { 26 _numberb = value; 27 } 28 } 29 public virtual double getresult() 30 { 31 double result = 0; 32 return result; 33 } 34 }
简单工厂类:
1 public class operationfactory 2 { 3 public static operation createoperate(string operate) 4 { 5 operation oper = null; 6 switch (operate) 7 { 8 case "+": 9 oper = new operationadd(); 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 }
加法类,继承operation:
1 class operationadd:operation 2 { 3 public override double getresult() 4 { 5 double result = 0; 6 result = numbera + numberb; 7 return result; 8 } 9 }
减法类,继承operation:
1 class operationsub:operation 2 { 3 public override double getresult() 4 { 5 double result = 0; 6 result = numbera - numberb; 7 return result; 8 } 9 }
乘法类,继承operation:
1 class operationmul : operation 2 { 3 public override double getresult() 4 { 5 double result = 0; 6 result = numbera * numberb; 7 return result; 8 } 9 }
除法类,继承operation:
1 class operationdiv : operation 2 { 3 public override double getresult() 4 { 5 double result = 0; 6 if (numberb==0) 7 { 8 throw new exception("除数不能为0。"); 9 } 10 result = numbera / numberb; 11 return result; 12 } 13 }
调用:
1 private void button1_click(object sender, eventargs e) 2 { 3 operation oper = operationfactory.createoperate(textbox4.text); 4 oper.numbera =convert.todouble(textbox1.text); 5 oper.numberb = convert.todouble(textbox2.text); 6 textbox3.text = oper.getresult().tostring(); 7 }
上一篇: 小伙你太幽墨
下一篇: 三篇文章带你极速入门php(一)之语法