设计模式之☞简单工厂模式
通过多态制作一个简单的计算器
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 }