案例:计算车费
思路: 我们提取一个公共Interface来计算费用三个不同类实现计费接口,再用一个公 共类管理三种不同车辆的计费功能
/**
* 计算价格
*
* @author MtmWp
*/
public abstract interface IPrice {
/**
* 返回计算后的价格
* @param path
* @return
*/
String countPrice(int path);
}
2.公交车,出租车,小汽车各自计费类
/**
* 公交车计算价格
*
* @author MtmWp
*
*/
public class BusCost implements IPrice {
@Override
public String countPrice(int path) {
return path*2+"";
}
}
/**
* 出租车计算价格
*
* @author MtmWp
*
*/
public class CarCost implements IPrice {
@Override
public String countPrice(int path) {
return path*2+5+"";
}
}
/**
* 小汽车计算价格
*
* @author MtmWp
*
*/
public class TaxiCost implements IPrice {
@Override
public String countPrice(int path) {
return path*3+1+"";
}
}
3.统一管理车类型费用类
/**
* 统一管理车类型以及费用类
*
* @author MtmWp
*
*/
public class CountCostManager {
IPrice iPrice;
/**
* 设置车类型
*
* @param price
*/
public void setCostType(IPrice price){
iPrice = price;
}
/**
* 计算价格
*
* @param path
* @return
*/
public String countCost(int path){
return iPrice.countPrice(path);
}
}
测试用例
//-----------------公交车费用------------------
CountCostManager mCountCostManager = new CountCostManager();
mCountCostManager.setCostType(new BusCost());//设置车类型
String price = mCountCostManager.countCost(12);//根据路程算具体花销
System.err.println("公交车费用:"+price+"\n");
//-----------------小汽车费用------------------
mCountCostManager.setCostType(new CarCost());//设置车类型
System.err.println("小汽车费用:"+mCountCostManager.countCost(12)+"\n");
//-----------------出租车费用------------------
mCountCostManager.setCostType(new TaxiCost());//设置车类型
mCountCostManager.countCost(12);//根据路程算具体花销
System.err.println("出租车费用:"+mCountCostManager.countCost(12)+"\n");
输出:
公交车费用:24
小汽车费用:29
出租车费用:37