练习题_已知出租车的计费规则如下
程序员文章站
2022-03-19 13:07:14
...
- 使用多态和接口区分两个不同时间段的收费机制。
- 使用工厂方法决定实例化哪个类。
- 计算即可
测试的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};
}
}
上一篇: 怕不怕鬼
推荐阅读