一、策略模式的简介
1.1、定义
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
1.2、使用场景
- 针对同一类型问题的多种处理方式,仅仅是具体行为有差别时;
- 需要安全地封装多种同一类型的操作时。
- 出现同一抽象类有多个子类,而又需要使用if-else或者switch-case来选择具体子类时。
二、策略模式的简单实现
示例:公交车和地铁的价格计算方式是不一样的,需要计算乘不同出行工具的成本,下面是第一版的代码:
public class PriceCalculator {
//公交车类型
private static final int BUS = 1;
//地铁类型
private static final int SUBWAY = 2;
public static void main(String[] args) {
PriceCalculator calculator = new PriceCalculator();
System.out.println("坐16公里的公交车票价为:" + calculator.calculatePrice(16, BUS));
System.out.println("坐16公里的地铁票价为:" + calculator.calculatePrice(16, SUBWAY));
}
/**
* 北京公交车,十公里之内一元钱,超过十公里之后每加一元钱可以乘5公里
*
* @param km
* @return
*/
private int busPrice(int km) {
//超过十公里的总距离
int extraTotal = km - 10;
//超过的距离是5公里的倍数
int extraFactor = extraTotal / 5;
//超过的距离对5公里取余
int fraction = extraTotal % 5;
//价格计算
int price = 1 + extraFactor * 1;
return fraction > 0 ? ++price : price;
}
/**
* 6公里(含)内3元;6~12公里(含)4元;12~22公里(含)5元;22~32公里(含)6元;
* @param km
* @return
*/
private int subwayPrice(int km) {
if (km <= 6) {
return 3;
} else if (km > 6 && km <= 12) {
return 4;
} else if (km > 12 && km <= 22) {
return 5;
} else if (km > 22 && km <= 32) {
return 6;
}
return 7;
}
int calculatePrice(int km, int type) {
if (type == BUS) {
return busPrice(km);
} else if (type == SUBWAY) {
return subwayPrice(km);
}
return 0;
}
}
输出结果:
策略模式1.png此时的代码已经比较混乱,各种if-else语句缠绕其中。当价格的计算方法变化时,需要直接修改这个类中的代码,很容易引入错误。
这类代码必然是难以应对变化的,它会使得代码变得越来越臃肿,难以维护。
用策略模式对上述示例进行重构:
/**
* 计算接口
*/
public interface CalculateStrategy {
/**
* 按距离来计算价格
* @param km
* @return
*/
int calculatePrice(int km);
}
//公交车价格计算策略
public class BusStrategy implements CalculateStrategy {
/**
* 北京公交车,十公里之内一元钱,超过十公里之后每加一元钱可以乘5公里
* @param km
* @return
*/
@Override
public int calculatePrice(int km) {
//超过十公里的总距离
int extraTotal = km - 10;
//超过的距离是5公里的倍数
int extraFactor = extraTotal / 5;
//超过的距离对5公里取余
int fraction = extraTotal % 5;
//价格计算
int price = 1 + extraFactor * 1;
return fraction > 0 ? ++price : price;
}
}
public class SubwayStrategy implements CalculateStrategy {
@Override
public int calculatePrice(int km) {
if (km <= 6) {
return 3;
} else if (km > 6 && km <= 12) {
return 4;
} else if (km > 12 && km <= 22) {
return 5;
} else if (km > 22 && km <= 32) {
return 6;
}
return 7;
}
}
再创建一个扮演Context角色的类
public class TranficCalculator {
public static void main(String[] args) {
TranficCalculator calculator = new TranficCalculator();
//设置计算策略
calculator.setStrategy(new BusStrategy());
//计算价格
System.out.println("坐16公里的公交车票价为:"+calculator.calculatePrice(16));
}
CalculateStrategy mStrategy;
public void setStrategy(CalculateStrategy mStrategy) {
this.mStrategy = mStrategy;
}
public int calculatePrice(int km) {
return mStrategy.calculatePrice(km);
}
}
这种方案在隐藏实现的同时,可扩展性变得很强。在简化逻辑、结构的同时,增强了系统的可读性、稳定性、可扩展性,这对于较为复杂的业务逻辑显得更为直观,扩展也更为方便。
三、总结
策略模式主要用来分离算法,在相同的行为抽象下有不同的具体实现策略。这个模式很好地演示了开闭原则,也就是定义抽象,注入不同的实现,从而达到很好的可扩展性。
3.1、优点
- 结构清晰明了、使用简单直观;
- 耦合度相对而言较低,扩展方便;
- 操作封装也更为彻底,数据更为安全。
3.2、缺点
- 随着策略的增加,子类也会变得繁多。