# 例子

``````public interface CalculateStrategy {

int calculatePrice(int km);

}
``````

``````public class BusStrategy implements CalculateStrategy {

//十公里以内一元钱，超过十公里后每加一元可多乘 5公里
@Override
public int calculatePrice(int km) {
int extraTotal = km - 10;
int extraFactor = extraTotal / 5;
int fraction = extraTotal % 5;
int price = 1 + extraFactor;
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 TaxiStrategy implements CalculateStrategy {

//出租车的价格
@Override
public int calculatePrice(int km) {
if(km < 10){
return 10;
}else{
int i = km-10;
return 10 + i*3;
}
}

}
``````

``````public class TranficCalculator {

CalculateStrategy mStrategy ;

public void setStrategy(CalculateStrategy mStrategy) {
this.mStrategy = mStrategy;
}

public int calculatePrice (int km){
return mStrategy.calculatePrice(km);
}
}
``````

``````public class Main {
public static void main(String[] args) {
TranficCalculator tranficCalculator = new TranficCalculator();
//这里使用不同的类 达到使用不同的策略。
tranficCalculator.setStrategy(new BusStrategy());
int busPrice = tranficCalculator.calculatePrice(20);
tranficCalculator.setStrategy(new SubwayStrategy());
int subwayPrice = tranficCalculator.calculatePrice(20);
tranficCalculator.setStrategy(new TaxiStrategy());
int taxiPrice = tranficCalculator.calculatePrice(20);
System.out.println("busPrice:"+busPrice);
System.out.println("subwayPrice:"+subwayPrice);
System.out.println("taxiPrice:"+taxiPrice);
}
}
``````

busPrice:3

subwayPrice:5

taxiPrice:40

# 优缺点

### 优点

1. 结构清晰明了、使用简单直观；
2. 耦合度相对而言较低，扩展方便；
3. 操作封装也更为彻底，数据更为安全。