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

2016-10-20  本文已影响6人  leiiiooo
定义:
通用类图:
策略模式通用类图
/*
 * 抽象的策略模式
 * */
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();// 高层模块实现对底层算法模块细节的屏蔽
  }
}
优点:
缺点:
上一篇 下一篇

猜你喜欢

热点阅读