本程序主要实现加法和减法2种运算,要实现别的运算请扩展该运算方法和修改操作工厂类!
操作类:
class Operation { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double getResult() { return 0.0; } } class OperationAdd : Operation { public override double getResult() { return NumberA + NumberB; } } class OperationSub : Operation { public override double getResult() { return NumberA - NumberB; } }
操作工厂类:
class OperationFactory { public static Operation createOperate(string operate) { Operation o = null; switch (operate) { case "+": o = new OperationAdd(); break; case "-:": o = new OperationSub(); break; } return o; } }
UI调用实现:
static void Main(string[] args) { Operation oper = OperationFactory.createOperate("+"); oper.NumberA = 3; oper.NumberB = 5; Console.WriteLine(oper.getResult()); }