class Operation { private double num1; private double num2; public double Num1 { get { return num1; } set { num1 = value; } } public double Num2 { set { num2=value; } get { return num2; } } public virtual double GetResult() { double result = 0; return result; } } class OperationAdd : Operation { public override double GetResult() { double result = 0; result = Num1 + Num2; return result; } } class OperationSub : Operation { public override double GetResult() { double result = 0; result = Num1 - Num2; return result; } } class OperationMul : Operation { public override double GetResult() { double result = 0; result = Num1 * Num2; return result; } } class OperationDiv : Operation { public override double GetResult() { double result = 0; result = Num1 / Num2; return result; } } class OperationFactory { public static Operation creatOperate( string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } }
客户端代码:
Operation oper; oper = OperationFactory.createOperate("+"); oper.Num1 = 1; oper.Num2 = 2; double result = oper.GetResult();