设计模式(三)策略模式

策略模式

  • 策略模式比简单工程模式有更高的抽象,将switch判断从业务逻辑中抽离出来,由策略类进行具体执行。更加方便增加多的策略(算法)
 enum OperationType  // 操作类型
    {
        Add,
        Square
    }
    class Operation     // 操作父类
    {
        protected double m_A;

        protected double m_B;

        public virtual double GetResult()
        {
            return 0;
        }
    }
    class OperationAdd : Operation  // 操作子类 Add
    {
        public OperationAdd(double A, double B)
        {
            m_A = A;
            m_B = B;
        }
        public override double GetResult()
        {
            return m_A + m_B;
        }
    }
    class OperationSquare : Operation  // 操作子类 Square
    {
        public OperationSquare(double A)
        {
            m_A = A;
        }
        public override Double GetResult()
        {
            return Math.Pow(m_A, 2);
        }
    }

    class Content // 上下文类
    {
        Operation op = null;

        public Content(OperationType type, double A, double B = 0f)
        {
            switch (type)
            {
                case OperationType.Add:
                    op = new OperationAdd(A, B);
                    break;
                case OperationType.Square:
                    op = new OperationSquare(A);
                    break;
            }
        }
        public double GetResult()
        {
            return op.GetResult();
        }
    }

    public void Main()  // 主方法
    {
        Content add = new Content(OperationType.Add, 1, 2);
        Content square = new Content(OperationType.Square, 2);
        add.GetResult();    // 1+2
        square.GetResult(); // 2*2
    }

posted @ 2019-12-27 16:43  ZeroyiQ  阅读(149)  评论(0编辑  收藏  举报