《大话设计模式》(二)简单工厂模式

简单工厂模式

  • 用来管理创造实例
// 操作类
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 OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }
// 工厂类,用来控制创造操作实例
public class OperationFactory
    {
        public static Operation CreateOperate (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;
                default:
                    throw new Exception("请输入正确的运算符!");

            }
       
            return oper;

        }
    }
Console.Write("请输入数字A:");
                string strNumberA = Console.ReadLine();
                Console.Write("请输入运算符(+、-、*、/):");
                string strOperate = Console.ReadLine();
                Console.Write("请输入数字B:");
                string strNumberB = Console.ReadLine();

                Operation oper = OperationFactory.CreateOperate(strOperate);
                oper.NumberA = Convert.ToDouble(strNumberA);
                oper.NumberB = Convert.ToDouble(strNumberB);
                double result = oper.GetResult();
                Console.WriteLine(oper.NumberA + strOperate  + oper.NumberB + "=" + result);
                Console.ReadLine();

《大话设计模式》(二)简单工厂模式

上一篇:UFUN函数 UF_UI_ONT UF_OPER函数(对当前程序进行操作)(UF_UI_ONT_ask_selected_nodes、UF_OPER_ask_cutter_group等)


下一篇:用栈实现多项式的计算(java语言实现)