示例#1
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("输入数字1");
                double num1 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("输入运算符");
                string opr = Console.ReadLine();
                Console.WriteLine("输入数字2");
                double num2 = Convert.ToDouble(Console.ReadLine());
                //简单工程模式
                // Calculate cal = CalculateFactory.CreateOperate(opr);

                //工厂模式
                IoperateFactory opration = new IAddFactory();
                Calculate       cal      = opration.CreateOperate();

                cal.Num1 = num1;
                cal.Num2 = num2;
                double result = cal.GetResult();
                Console.WriteLine(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
        public static Calculate CreateOperate(string opr)
        {
            // Calculate cal = null;
            IoperateFactory orpfactry = null;

            switch (opr)
            {
            case "+":
                //cal = new Add();
                orpfactry = new IAddFactory();
                break;

            case "-":
                //cal = new Sub();
                orpfactry = new ISubFactory();
                break;

            case "*":
                //cal = new Mul();
                orpfactry = new IMulFactory();
                break;

            case "/":
                //cal=new Div();
                orpfactry = new IDivFactory();
                break;

            default:
                throw new Exception("运算符不存在");
                break;
            }

            //return cal;
            return(orpfactry.CreateOperate());
        }