在我的理解中,strategy设计模式就是能够实现整体地替换某个算法去解决同一个问题的一种编程模式。举个例子,我们从A地到B地,可以坐车,可以步行,可以骑自行车,但这三种方式都是出行的一种形式,因此,我们可以设计一个出行的接口,然后三种方法分别是接口的具体实现类。
具体结构可以概括为下面这张图:
Context类可以理解为将接口封装的一个类,在使用的时候,只需要声明一个Context类,就可以委派这个类实现接口的不同操作。
在软件构造lab6中,我们需要设计不同的过河策略,为每个待过河的猴子分配某个策略,这时候strategy模式非常方便。
package strategy;
import ladder.Ladder;
public interface ChooseLadderStrategy {
/**
* get a ladder for monkey.
*
* @return a accessible ladder.
*/
public Ladder getLadder(String derection);
/**
* return the ladder to the collection.
*
* @param ladder - ladder has been changed.
* @return true only if success.
*/
public boolean returnLadder(Ladder ladder);
}
然后分别完善不同的策略,实现接口中的两个方法,将接口封装进Context类即可。
package strategy;
import ladder.Ladder;
public class ChooseLadderContext{
ChooseLadderStrategy strategy;
public ChooseLadderContext(ChooseLadderStrategy strategy){
this.strategy = strategy;
}
public Ladder getLadder(String direction){
this.strategy.getLadder(derection);
}
public boolean returnLadder(Ladder ladder){
this.strategy.returnLadder(ladder);
}
}
小结: Strategy模式是最常用的设计模式之一,Context和Strategy之间是委托的弱关联关系,Context委托ConcreteStrategy实例去实现具体的策略。
参考链接:https://blog.youkuaiyun.com/SomeoneMH/article/details/80591370