设计模式-策略模式简单理解

先看一段简单的代码:
class A{
    public void doAction(int type){
      .......//其他代码
        if(type ==0){  do action0; return; }
        if(type ==1){  do action1; return; }
        if(type ==2){  do action2; return; }
        ...
        if(type ==n){  do action4; return; }
        .......//其他代码
    }
}
client:
    new A().doAction(0);
 
相信都遇到过这样的代码吧,这样会有什么问题呢?
问:如果需要增加新的行为action怎么办?
答:修改doAction方法。
问:还有没有其他办法呢?
答:可以继承A,重载其doAction方法。
问:可以,但是重载A后,如果A的其他方法发生了变化会直接影响到其子类,这样引入了新的问题。
 
如何做到增加一个新的Action而不影响其他的代码呢?
首先,定义一个接口:
interface Action{
    do();
}
然后,定义其实现类
class Action0 implements Action{
    do(){实现action0操作}
}
class Action1 implements Action{
    do(){实现action1操作}
}
class Action2 implements Action{
    do(){实现action2操作}
}
。。。
 
修改调用者上下文:
class A{
    Action action = null;
    setAction(Action action){this.action = action;}
    doAction(){
           ...
        action.do();
           ...
    }
}
client:在使用A时动态设置其Action对象。
    A a =new A();
    a.setAction(new Action0());  //动态设置其Action对象
    a.doAction();
 
这样,即使再增加Action的操作,只需要新增一个Action接口的实现类。而不用修改调用者A的任何代码。
 
这就是策略模式的使用,策略模式包含两个角色: 
  Context:使用策略的上下文,也就是例子中类A。
  Strategy:策略类,也就是例子中的Action接口。
 
策略模式是非常简单的一个模式,就是把行为提取成一个接口,从而把行为和使用者解耦,行为的增加或者变化不会影响到使用者的代码。
 
 

posted on 2018-12-28 18:29  SimpleWorker  阅读(185)  评论(0编辑  收藏  举报

导航