1 定义
策略模式(Strategy Pattern),就是把一组具有相同目的实现方式不一样的算法集中起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。
2 优点
1.多重条件语句不易维护,而使用策略模式可以避免使用多重条件语句,如 if...else 语句、switch...case 语句。
2.策略模式提供了一系列的可供重用的算法族,恰当使用继承可以把算法族的公共代码转移到父类里面,从而避免重复的代码。
3.策略模式可以提供相同行为的不同实现,客户可以根据不同时间或空间要求选择不同的。
4.策略模式提供了对开闭原则的完美支持,可以在不修改原代码的情况下,灵活增加新算法。
5.策略模式把算法的使用放到环境类中,而算法的实现移到具体策略类中,实现了二者的分离。
6.策略模式结合工厂模式,可以降低客户端类与算法抽象的耦合。
3 例子讲解
依据天气情况,每天上班可以有不同的策略。天气晴朗,骑自行车上班,下雨,坐地铁上班,刮大风,开车上班,下雪,步行上班。客户端根据天气情况,选择不同的上班策略。
4 UML类图
5 示例代码
5.1 WayToWorkStrategy接口
public interface WayToWorkStrategy {
/**
* 如何去上班
* @return 上班方式
*/
String chooseWayToWork();
}
5.2 BicycleWay自行车
public class BicycleWay implements WayToWorkStrategy{
@Override
public String chooseWayToWork() {
return "骑自行车去上班";
}
}
5.3 CarWay小汽车
public class CarWay implements WayToWorkStrategy{
@Override
public String chooseWayToWork() {
return "开车去上班";
}
}
5.4 SubwayWay地铁
public class SubwayWay implements WayToWorkStrategy{
@Override
public String chooseWayToWork() {
return "坐地铁去上班";
}
}
5.5 WalkWay走路
public class WalkWay implements WayToWorkStrategy{
@Override
public String chooseWayToWork() {
return "走路去上班";
}
}
5.6 ContextStrategy策略对象的引用
public class ContextStrategy {
private String climate;
WayToWorkStrategy wayToWorkStrategy;
public ContextStrategy(String climate){
this.climate = climate;
this.wayToWorkStrategy = chooseContextStrategy();
}
private WayToWorkStrategy chooseContextStrategy(){
//简单工厂模式
switch (climate) {
case "sun":
return new BicycleWay();
case "rain":
return new SubwayWay();
case "wind":
return new CarWay();
case "snow":
return new WalkWay();
default:
return null;
}
}
/**
* 获取上班策略
* @return 上班策略
*/
public String showWayToWork(){
if (wayToWorkStrategy == null){
return "天气不符合要求,无法上班,好开心";
}
return wayToWorkStrategy.chooseWayToWork();
}
}
5.7 MainClass主函数
public class MainClass {
public static void main(String[] args) {
boolean flag = true;
while (flag) {
//模拟天气参数
Scanner sc = new Scanner(System.in);
String climate = sc.nextLine();
if (climate.equals("exit")) {
flag = false;
} else {
ContextStrategy strategy = new ContextStrategy(climate);
System.out.println(strategy.showWayToWork());
}
}
}
}
5.8 运行结果
6 引用
1.《大话设计模式》
7 源代码
https://github.com/airhonor/design-pattern-learning/tree/main/src/com/hz/design/pattern/strategy