You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
homework/PercentageDiscountStrategy....

29 lines
1017 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

public class PercentageDiscountStrategy implements DiscountStrategy {
private double discountPercentage; // 折扣百分比例如0.1表示10%折扣
/**
* 构造百分比折扣策略
* @param discountPercentage 折扣百分比0-1之间的值
*/
public PercentageDiscountStrategy(double discountPercentage) {
if (discountPercentage < 0 || discountPercentage > 1) {
throw new IllegalArgumentException("折扣百分比必须在0到1之间");
}
this.discountPercentage = discountPercentage;
}
@Override
public double calculateDiscount(Order order) {
if (order == null) {
return 0;
}
// 计算折扣金额:订单金额 * 折扣百分比
return order.getAmount() * discountPercentage;
}
@Override
public String getDescription() {
// 将百分比转换为整数表示例如0.1转换为10%
return (int)(discountPercentage * 100) + "%折扣";
}
}