美文网首页
<<设计模式之禅(第二版)>>——第十八

<<设计模式之禅(第二版)>>——第十八

作者: leiiiooo | 来源:发表于2016-10-20 09:48 被阅读6次
定义:
  • 定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。
通用类图:
策略模式通用类图
/*
 * 抽象的策略模式
 * */
public abstract class Strategy {
  abstract void doSomething();
}
/*
 * 定义具体的策咯模式
 * */
public class ConcreteStrategyOne extends Strategy {

  @Override
  void doSomething() {
    // TODO Auto-generated method stub

   }

}
public class ConcreteStrategyTwo extends Strategy {

  @Override
  void doSomething() {
    // TODO Auto-generated method stub

  }

}
/*
 * 定义上下文角色,用来封装对象
 * */
public class Context {
  private Strategy strategy;

  public Context(Strategy strategy) {
    // TODO Auto-generated constructor stub
    this.strategy = strategy;
  }

  public void doAnything() {
    this.strategy.doSomething();
  }
}
public class Client {
  public static void main(String[] args) {
    Strategy strategyOne = new ConcreteStrategyOne();
    Context context = new Context(strategyOne);
    context.doAnything();// 高层模块实现对底层算法模块细节的屏蔽
  }
}
优点:
  • 算法可以自由切换
  • 避免本身实现多重条件的判断,由外部条件决定当前应该使用哪一种算法
  • 拓展性良好
缺点:
  • 策略类数量增多
  • 所有的策略类都需要对外暴露

相关文章

网友评论

      本文标题:<<设计模式之禅(第二版)>>——第十八

      本文链接:https://www.haomeiwen.com/subject/junzyttx.html