我们在解决一个问题有多种方案的时候最简单的方式就是通过if-esle或者switch-case方法我们来个简单的实例:在2014年12月28号,北京提高公交价格, 不再是单一票价制,采用分段制,公交和地铁价格的计算方式也不一样.我们就来计算乘坐不同工具的成本
开始撸代码
public class PriceCalculator {
public static final int BUS = 1;
public static final int SUBWAY = 1;
public static void main(String[] args) {
}
/**
* 北京公家车, 十公里之内一元钱,超过十公里之后每加一公里可以乘坐5公里
* @param km
* @return
*/
private int busPrice(int km) {
//超过十公里的总距离
int extraTal = km - 10;
//超过的距离是5公里的倍数
int extraFactor = extraTal / 5;
//超过5公里取余
int fraction = extraTal % 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;
}
private int calculatePrice(int km, int type) {
if (type == BUS) {
return busPrice(km);
} else if (type == SUBWAY) {
return subWayPrice(km);
}
return 0;
}
}
我想刚开始我们都会这么写 很简单, 看下这个类承担了计算公交车和地铁价格的问题;不是单一职责,另一个问题就是通过if-else来判断哪种计算形式.当我们增加一种出行方式的时候,我们就要写一个方法来计算, 而且还要在calculatePrice(int km, int type)方法中增加一个判断
用策略模式进行重构
计算接口
public interface CalculateStrategy {
/**
* 按距离来计算价格
* @param km 公里
* @return 返回价格
*/
int calculatePrice(int km);
}
公交车计算策略
public class BusStrategy implements CalculateStrategy {
@Override
public int calculatePrice(int km) {
//超过十公里的总距离
int extraTal = km - 10;
//超过的距离是5公里的倍数
int extraFactor = extraTal / 5;
//超过5公里取余
int fraction = extraTal % 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;
}
}
管理类
public class TranficCalcultaor {
CalculateStrategy mCalculateStrategy;
public void setStrategy(CalculateStrategy calculateStrategy) {
mCalculateStrategy = calculateStrategy;
}
public int calculatePrice(int km) {
return mCalculateStrategy.calculatePrice(km);
}
}
使用
public static void main(String[] args) {
TranficCalcultaor tranficCalcultaor = new TranficCalcultaor();
tranficCalcultaor.setStrategy(new BusStrategy());
int i = tranficCalcultaor.calculatePrice(16);
System.out.println(i+"===============");
}
安卓系统中用到策略模式的有:时间插值器