首页 > 代码库 > 策略模式(Strategy Method)

策略模式(Strategy Method)

  策略模式可以看做“可插入式算法(Pluggable)”,将子类各自的行为和公共的逻辑分离开来,将子类的行为抽象为算法插入到公共的逻辑中,这样替换子类的行为也不会对公共逻辑产生影响,也不会影响到调用类的逻辑。

  

  下面是一个策略模式的简单例子,类图如下:

       

         公共逻辑Context的代码如下:

public class Context{    public void contextInterface(){    //add common code here        strategy.strategyInterface();    //add common code here    }    /**     * @link aggregation     * @directed      */    private Strategy strategy;    private void setStrategy (Strategy strategy){    this.strategy = strategy;    }    private Strategy getStrategy (){    return this.strategy;    }}

  子类算法的接口如下:

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

  具体的算法如下:

public class ConcreteStrategy extends Strategy{    public void strategyInterface(){        //write you algorithm code here    }}

  当我们希望修改具体算法中的实现,我们只要重写一个类,继承Strategy接口,Context中的公共逻辑不需要修改。

 

      Java中策略模式的例子:

  环境角色由Container扮演,算法接口由LayoutManager扮演,具体算法由GridBagLayout、GridLayout等扮演。

策略模式(Strategy Method)