外卖平台接口类
public interface Takeaway {
// 计算总费用
double getTotalMoney(List<Shop> shops);
// 计算优惠费用
double getDiscountMoney(double totalMoney);
}
美团实现类
public class Meituan implements Takeaway {
@Override
public double getTotalMoney(List<Shop> shops) {
double sum = 0;
for (Shop shop : shops) {
sum += shop.getPrice() * shop.getCount();
}
return sum;
}
@Override
public double getDiscountMoney(double totalMoney) {
Random r = new Random();
double sum = 0;
int n = (int) (totalMoney / 50);
for (int i = 0; i < n; i++) {
// 随机生成15以内优惠券并相加,精确到小数点后两位
sum += (r.nextInt(1500) + 1) / 100.0;
}
return sum;
}
}
饿了么实现类
public class Eleme implements Takeaway {
@Override
public double getTotalMoney(List<Shop> shops) {
double sum = 0;
for (Shop shop : shops) {
sum += shop.getPrice() * shop.getCount();
}
return sum;
}
@Override
public double getDiscountMoney(double totalMoney) {
Random r = new Random();
double sum = 0;
if (totalMoney > 100) {
// 随机生成25以内优惠券并相加,精确到小数点后两位
sum = (r.nextInt(2500) + 1)/100.0;
}
return sum;
}
}
测试类main方法
public static void main(String[] args) {
Shop s1 = new Shop(30, 3);
Shop s2 = new Shop(12, 3);
Shop s3 = new Shop(13, 2);
Shop s4 = new Shop(15, 3);
List<Shop> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
Takeaway t1 = new Meituan();
double totalMoney1 = t1.getTotalMoney(list);
double discountMoney1 = t1.getDiscountMoney(totalMoney1);
System.out.println("美团需要付钱总数:" + (totalMoney1 - discountMoney1) + ",共优惠了:" + discountMoney1);
Takeaway t2 = new Eleme();
double totalMoney2 = t2.getTotalMoney(list);
double discountMoney2 = t2.getDiscountMoney(totalMoney1);
System.out.println("饿了么需要付钱总数:" + (totalMoney2 - discountMoney2) + ",共优惠了:" + discountMoney2);
}
运行截图