欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

练习题_已知出租车的计费规则如下

程序员文章站 2022-03-19 13:07:14
...

练习题_已知出租车的计费规则如下

  1. 使用多态和接口区分两个不同时间段的收费机制。
  2. 使用工厂方法决定实例化哪个类。
  3. 计算即可

测试的Main方法

package tax;

import java.util.Scanner;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:00
 */
public class CalculateMoney {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        double miles = input.nextDouble();
        BaseTime time = TimeFactory.getTime();
        System.out.println(time.calculate(miles));
    }
}

工厂类

package tax;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:05
 */
public class TimeFactory {
    public static final LocalTime START = LocalTime.of(6, 0);
    public static final LocalTime END = LocalTime.of(23, 0);

    public static BaseTime getTime() {
        if (LocalTime.now().isAfter(START) && LocalTime.now().isBefore(END)) {
            return new NormalTime();
        } else {
            return new ExtraTime();
        }
    }
}

接口类

package tax;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:04
 */
public interface Time {
    double[] getBalanceByMiles();
}

实现接口的抽象类

package tax;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:23
 */
public abstract class BaseTime implements Time {
    private static final double START = 3;
    private static final double END = 15;

    public double calculate(double miles) {
        double[] mileMoneyList = this.getBalanceByMiles();
        double result = mileMoneyList[0];

        if (miles - END > 0) {
            result += (miles - END) * mileMoneyList[2];
            miles = END;
        }
        if (miles - START > 0) {
            result += (miles - START) * mileMoneyList[1];
        }

        return result;
    }
}

正常时间段类6.00-23.00

package tax;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:05
 */
public class NormalTime extends BaseTime {
    private static final double BASE_MONEY = 10;

    @Override
    public double[] getBalanceByMiles() {
        return new double[]{BASE_MONEY, 1.2, 2};
    }
}

其他时间段类

package tax;

/**
 * @author 青韵
 * @date 2020/3/7 - 13:23
 */
public class ExtraTime extends BaseTime {
    private static final double BASE_MONEY = 12;

    @Override
    public double[] getBalanceByMiles() {
        return new double[]{BASE_MONEY, 1.4, 3};
    }
}

相关标签: 小练习题