设计模式(二)简单工厂模式和工厂方法模式

简单工厂模式

  • 用来管理创造实例,解决对象创建
    通过子类自动向上转型为父类的特性,可以通过父类控制不同子类,调用相应子类的实现方法来实现不同的操作。
// 操作类
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();

工厂方法模式

因为简单工厂模式违背了开放-封闭原则。不但开放了扩展(新增操作类),还开放了修改(工厂类)因此需要使用工厂方法模式封闭修改。
对于工厂类,抽象出来接口,用来创建对应产品的方法,将原来修改工厂类,该为了增加对应的工厂类。

//  抽象接口
public interface IFactory
{
    public Operation CreateOperation();
}
// 工厂
public class AddFactory : IFactory
{
    public Operation CreateOperation()
    {
        return new OperationAdd();
    }
}
    Console.Write("请输入数字A:");
    string strNumberA = Console.ReadLine();
    Console.Write("请输入数字B:");
    string strNumberB = Console.ReadLine();

    IFactory factory = new AddFatory();
    Operation oper = factory.CreateOperation();
    oper.NumberA = Convert.ToDouble(strNumberA);
    oper.NumberB = Convert.ToDouble(strNumberB);
    double result = oper.GetResult();

posted @ 2019-12-26 14:57  ZeroyiQ  阅读(158)  评论(0编辑  收藏  举报