日期:2014-05-20 浏览次数:20809 次
namespace 简单工厂 { public class Operation { private double _leftNum; public double LeftNum { get { return _leftNum; } set { _leftNum = value; } } private double _rightNum; public double RightNum { get { return _rightNum; } set { _rightNum = value; } } public virtual double GetResule() { return 0.0; } } public class OperationAdd : Operation { public override double GetResule() { double result = 0; result = LeftNum + RightNum; return result; } } public class OperationSub : Operation { public override double GetResule() { double result = 0; result = LeftNum + RightNum; return result; } } public class OperationMul : Operation { public override double GetResule() { double result = 0; result = LeftNum * RightNum; return result; } } public class OperationDiv : Operation { public override double GetResule() { double result = 0; if (LeftNum == 0) { throw new Exception("除数不能为 0。"); } result = LeftNum / RightNum; return result; } } public class OperationSqr : Operation { public override double GetResule() { double result = 0; result = LeftNum * LeftNum; return result; } } public class OperationSqrt : Operation { public override double GetResule() { double result = 0; if (LeftNum == 0) { throw new Exception("负数不能开平方根。"); } result = Math.Sqrt(LeftNum); return result; } } public class OperationReverse : Operation { public override double GetResule() { double result = 0; result = -LeftNum; return result; } } public class OperationFactory { public static Operation createOperate(string operate) { Operation op = null; switch (operate) { case "+": { op = new OperationAdd(); break; } case "-": { op = new OperationSub(); break; } case "*": { op = new OperationMul(); break; } case "/": { op = new OperationDiv(); break; } case "sqr": { op = new OperationSqr(); break; } case "sqrt": { op = new OperationSqrt(); break; } case "+/-": { op = new OperationReverse(); break; } } return op; } } }