策略模式(Strategy Pattern)

摘自:算法

策略模式(Strategy):它定义了一系列的算法,并将每个算法封装起来,并且使它们还能够相互替换。策 略模式让算法的变化不会影响到使用算法的客户。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)ide

 

 

图1 策略模式类图单元测试

 优势:测试

  一、 简化了单元测试,由于每一个算法都有本身的类,能够经过本身的接口单独测试。
  二、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
      三、 遵照大部分GRASP原则和经常使用设计原则,高内聚、低偶合。
this

  缺点:
  一、 由于每一个具体策略类都会产生一个新类,因此会增长系统须要维护的类的数量。
      二、 在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。(这自己没有解除客户端须要选择判断的压力,而策略 模式与简单工厂模式结合后,选择具体实现的职责也能够由Context来承担,这就最大化的减轻了客户端的压力。spa

代码:设计

    public abstract class Strategy
    {
        public abstract void strategyInterface();
    }

    public class ConcreteStrategy : Strategy
    {
        public override void strategyInterface()
        {
            Console.Write("ConcreteStrategy strategyInterface");
        } 
    }

    public class Context
    {
        private Strategy strategy = null;
        public Context(Strategy strtegy)
        {
            this.strategy = strategy;
        }
        public void contextInterface()
        {
            this.strategy.strategyInterface();
        }
    }

调用:code

  Context context = new Context(new ConcreteStrategy());
  context.contextInterface();
相关文章
相关标签/搜索