Strategic model case: Calculation of vehicle fare

Strategy mode

Case: Calculation of car fare

Idea: we extract a public Interface to calculate the cost, three different charging interfaces to implement the charging Interface, and then use a public class to manage the charging functions of three different vehicles

  • The common point of the three vehicle costs is to calculate the vehicle costs
  • The difference is the vehicle type
  • Bus fare
  • Taxi fare
  • Car fare

    1. Public billing interface

/**
 * Calculated price
 *
 * @author MtmWp
 */
public abstract interface IPrice {

    /**
     * Return the calculated price
     * @param path
     * @return
     */
    String countPrice(int path); 

}

2. Bus, taxi and car charging

 /**
 * Bus calculation price
 * 
 * @author MtmWp
 *
 */
public class BusCost implements IPrice {

    @Override
    public String countPrice(int path) {
        return path*2+"";
    }

}
/**
 * Taxi calculation price
 * 
 * @author MtmWp
 *
 */
public class CarCost implements IPrice {

    @Override
    public String countPrice(int path) {
        return path*2+5+"";

    }
/**
 * Car calculation price
 * 
 * @author MtmWp
 *
 */
public class TaxiCost implements IPrice {

    @Override
    public String countPrice(int path) {
        return path*3+1+"";

    }

3. Unified management of vehicle type expenses

/**
 * Unified management of vehicle types and expenses
 * 
 * @author MtmWp
 *
 */
public class CountCostManager {

    IPrice iPrice;

    /**
     * Set vehicle type
     * 
     * @param price
     */
    public void setCostType(IPrice price){
        iPrice = price;
    }

    /**
     * Calculated price
     * 
     * @param path
     * @return
     */
    public String countCost(int path){
        return iPrice.countPrice(path);
    }

test case

        //-----------------Bus cost------------------
        CountCostManager mCountCostManager  = new CountCostManager();
        mCountCostManager.setCostType(new BusCost());//Set vehicle type
        String price = mCountCostManager.countCost(12);//Calculate the specific cost according to the distance
        System.err.println("Bus cost:"+price+"\n");

        //-----------------Car expenses------------------
        mCountCostManager.setCostType(new CarCost());//Set vehicle type
        System.err.println("Car expenses:"+mCountCostManager.countCost(12)+"\n");

        //-----------------Taxi fee------------------
        mCountCostManager.setCostType(new TaxiCost());//Set vehicle type
        mCountCostManager.countCost(12);//Calculate the specific cost according to the distance
        System.err.println("Taxi fee:"+mCountCostManager.countCost(12)+"\n");

Output:

Bus cost: 24

Car cost: 29

Taxi fee: 37

Added by racerxfactor on Tue, 31 Mar 2020 15:34:26 +0300