运算类 public class yunsuan { public static operation create(string operate) { operation oper = null; switch (operate) { case "+": oper = new add(); break; case "-": oper = new sub(); break; case "*": oper = new cheng(); break; case "/": oper = new chu(); break; } return oper; } }
//类的属性 public class operation { private double numberA = 0; private double numberB = 0; public double NumberA { get { return numberA; } set { numberA = value; } } public double NumberB { get { return numberB; } set { numberB = value; } } public virtual double getresult() { double result = 0; return result; } } //类继承运算 class add : operation {//加法 public override double getresult() { double result = 0; result = NumberA + NumberB; return result; } } //减法 class sub : operation { public override double getresult() { double result = 0; result = NumberA - NumberB; return result; } } //乘法 class cheng : operation { public override double getresult() { double result = 0; result = NumberA * NumberB; return result; } } class chu : operation { public override double getresult() { double result = 0; if (NumberB == 0) { Console.WriteLine("被除数不能为0"); } result = NumberA / NumberB; return result; } }
客户端代码
//简单工厂模式 operation oper; oper = yunsuan.create("/"); oper.NumberA = 10; oper.NumberB = 10; double result = oper.getresult(); Console.WriteLine(result); Console.ReadKey();