public interface CalculateStrategy {
//根据距离计算价格
int calculatePrice(int km);
}
公交车计算
1
2
3
4
5
6
7
8
9
10
11
12
//公交车的价格计算策略
public class BudStrategy implements CalculateStrategy {
//10公里内1元,超过10公里每5公里加收1元
public int calculatePrice(int km) {
int extraTotal = km -10;
int extraFactor = extraTotal/5;
int fraction=extraTotal%5;
//价格计算,分段式计价
int price=1+extraFactor*1;
return fraction>0?++price:price;
}
}
地铁计算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//地铁的价格计算策略
public class SubwayStrategy implements CalculateStrategy {
public int calculatePrice(int km) {
//6公里内3元,6~12 4元 12~22 5元 22~32 6元
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;
}
//其他距离简化7元
return 7;
}
}
调用实现的测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class TranficCalculator {
public static void main(String[] args) {
TranficCalculator tranficCalculator=new TranficCalculator();
//设置策略
tranficCalculator.setCalculateStrategy(new BudStrategy());
int price=tranficCalculator.calculatePrice(16);
System.out.println("公交车乘坐16公里的价格"+price);
}
CalculateStrategy mCalculateStrategy;
public void setCalculateStrategy(CalculateStrategy calculateStrategy){
this.mCalculateStrategy=calculateStrategy;
}
public int calculatePrice(int km){
return mCalculateStrategy.calculatePrice(km);
}
}