疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java设计模式之策略模式


 

        1 概念

  策略模式(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.)

  1,策略接口

  [java] view plaincopy

  package com.strategy;

  public interface StrategyInterface {

  void dosomething();

  }

  2,具体的策略

  策略1:

  [java] view plaincopy

  package com.strategy;

  public class Strategy1Impl implements StrategyInterface{

  @Override

  public void dosomething() {

  System.out.println("use Strategy1 do something");

  }

  }

  策略2

  [java] view plaincopy

  package com.strategy;

  public class Strategy2Impl implements StrategyInterface{

  @Override

  public void dosomething() {

  System.out.println("use Strategy2 do something");

  }

  }

  策略3:

  [java] view plaincopy

  package com.strategy;

  public class Strategy3Impl implements StrategyInterface {

  @Override

  public void dosomething() {

  System.out.println("use Strategy3 do something");

  }

  }

  环境角色,上下文Contex

  [java] view plaincopy

  package com.strategy;

  public class StrategyContex {

  private StrategyInterface strategyInterface;

  public StrategyInterface getStrategyInterface() {

  return strategyInterface;

  }

  public void setStrategyInterface(StrategyInterface strategyInterface) {

  this.strategyInterface = strategyInterface;

  }

  public StrategyContex(StrategyInterface strategyInterface) {

  super();

  this.strategyInterface = strategyInterface;

  }

  public StrategyContex(){}

  public void doSomething(){

  this.strategyInterface.dosomething();

  }

  }

  客户端调用:

  [java] view plaincopy

  package com.strategy;

  public class MainClient {

  public static void main(String[] args) {

  StrategyContex contex = new StrategyContex();

  contex.setStrategyInterface(new Strategy1Impl());

  contex.doSomething();

  contex.setStrategyInterface(new Strategy2Impl());

  contex.doSomething();

  contex.setStrategyInterface(new Strategy3Impl());

  contex.doSomething();

  }

  }

  运行结果:

  use Strategy1 do something

  use Strategy2 do something

  use Strategy3 do something