码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式(Strategy Method)

时间:2014-12-13 23:19:50      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   sp   java   on   div   

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

  

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

        bubuko.com,布布扣

         公共逻辑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中策略模式的例子:

bubuko.com,布布扣

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

策略模式(Strategy Method)

标签:style   blog   http   io   color   sp   java   on   div   

原文地址:http://www.cnblogs.com/lnlvinso/p/4161997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!