电商优惠促销策略模式实现

策略模式是一种常见的设计模式,它可以灵活地定义和切换不同的策略,使得系统更加方便和可扩展。下面是一个简单的电商优惠促销策略模式的示例:

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 方法进行优惠计算。

通过使用优惠促销策略模式,我们可以方便地定义和切换不同的促销策略,使得电商系统对于不同促销活动的处理更加灵活和易于扩展。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值