策略模式是一种常见的设计模式,它可以灵活地定义和切换不同的策略,使得系统更加方便和可扩展。下面是一个简单的电商优惠促销策略模式的示例:
import java.math.BigDecimal;
// 促销策略接口
interface PromotionStrategy {
BigDecimal applyDiscount(BigDecimal amount);
}
// 满减促销策略
class FullReductionStrategy implements PromotionStrategy {
private BigDecimal fullAmount;
private BigDecimal reductionAmount;
public FullReductionStrategy(BigDecimal fullAmount, BigDecimal reductionAmount) {
this.fullAmount = fullAmount;
this.reductionAmount = reductionAmount;
}
@Override
public BigDecimal applyDiscount(BigDecimal amount) {
if (amount.compareTo(fullAmount) >= 0) {
return amount.subtract(reductionAmount);
}
return amount;
}
}
// 打折促销策略
class DiscountStrategy implements PromotionStrategy {
private BigDecimal discount;
public DiscountStrategy(BigDecimal discount) {
this.discount = discount;
}
@Override
public BigDecimal applyDiscount(BigDecimal amount) {
return amount.multiply(discount);
}
}
// 电商订单类
class Order {
private BigDecimal amount;
private PromotionStrategy promotionStrategy;
public Order(BigDecimal amount, PromotionStrategy promotionStrategy) {
this.amount = amount;
this.promotionStrategy = promotionStrategy;
}
public BigDecimal getTotalAmount() {
return promotionStrategy.applyDiscount(amount);
}
}
public class Main {
public static void main(String[] args) {
// 创建订单并选择促销策略
Order order1 = new Order(new BigDecimal("100"), new FullReductionStrategy(new BigDecimal("50"), new BigDecimal("10")));
Order order2 = new Order(new BigDecimal("200"), new DiscountStrategy(new BigDecimal("0.8")));
// 输出订单总金额
System.out.println("Order 1 total amount: " + order1.getTotalAmount()); // 输出:Order 1 total amount: 90
System.out.println("Order 2 total amount: " + order2.getTotalAmount()); // 输出:Order 2 total amount: 160
}
}
在上述示例中,我们定义了一个 PromotionStrategy 接口,表示优惠促销策略,包括满减策略和打折策略。然后,我们在 Order 类中引入了一个 PromotionStrategy 对象,通过构造函数传入具体的促销策略。在计算订单总金额时,直接调用 PromotionStrategy 的 applyDiscount 方法进行优惠计算。
通过使用优惠促销策略模式,我们可以方便地定义和切换不同的促销策略,使得电商系统对于不同促销活动的处理更加灵活和易于扩展。