本系列摘录于《大话设计模式》旨在记录学习过程,之前看的都忘记了,好在每天一个设计模式工作量也不太大

业务的封装是让业务逻辑与界面逻辑分开,降低耦合度

简单工厂模式:到底实例化谁,将来会不会增加实例化对象

例子:计算器

using System;
using System.Collections.Generic;
using System.Text;

namespace 简单工厂
{
    class Program
    {
        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;
            }
        }
        class OperationSub:Operation
        {
            public override double GetResult()
            {
                double result=0;
                result=NumberA-NumberB;
                return result;
            }
        }
        class OperationMul:Operation
        {
            public override double GetResult()
            {
                double result=0;
                result=NumberA*NumberB;
                return result;
            }
        }
        class OperationDiv:Operation
        {
            public override double GetResult()
            {
                double result=0;
                if(NumberB==0)
                    throw new Exception("除数不能为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;
                }
                return oper;
            }
        }

        static void Main(string[] args)
        {
            Operation oper;
            oper = OperationFactory.createOperate("+");
            oper.NumberA = 1;
            oper.NumberB = 2;
            double result = oper.GetResult();
            Console.WriteLine(result);
            Console.Read();
        }
    }
}