首页 > 代码库 > 策略模式(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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。