十分钟利用springboot写电商支持多种优惠券规则,使用策略模式替代大量的if

发布时间:2024-11-29 12:39

使用电子优惠券代替现金支付,部分商家可叠加使用 #生活技巧# #节省生活成本# #购物优惠技巧# #网购优惠策略#

前言            

        在开发电商折扣模块的时候经常会碰到各种优惠规则,那么就会碰到很多条件判断,冗余各种if-else的代码使得维护困难,此时就可以用策略模式来解决,替代大量的冗余判断条件代码,精简代码结构。
        策略模式是一种行为模式,也是替代大量ifelse的利器。它所能帮你解决的是场景,一般是具有同类可替代的行为逻辑算法场景。比如;不同类型的交易方式(信用卡、支付宝、微信)、生成唯一ID策略(UUID、DB自增、DB+Redis、雪花算法、Leaf算法)等,都可以使用策略模式进行行为包装,供给外部使用。

1、定义优惠券折扣接口类

public interface ICouponDiscount<T> {

BigDecimal discountAmount(T couponInfo, BigDecimal skuPrice);

}

2、实现折扣接口

满减规则

public class MJCouponDiscount implements ICouponDiscount<Map<String,String>> {

@Override

public BigDecimal discountAmount(Map<String, String> couponInfo, BigDecimal skuPrice) {

String x = couponInfo.get("x");

String y = couponInfo.get("y");

if(skuPrice.compareTo(new BigDecimal(x)) < 0){

return skuPrice;

}

BigDecimal discountAmount = skuPrice.subtract(new BigDecimal(y));

if(discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;

return discountAmount;

}

}

N元购规则

public class NYGCouponDiscount implements ICouponDiscount<Double> {

@Override

public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

return new BigDecimal(couponInfo);

}

}

折扣规则

public class ZKCouponDiscount implements ICouponDiscount<Double> {

@Override

public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

BigDecimal discountAmount = skuPrice.multiply(new BigDecimal(couponInfo)).setScale(2, BigDecimal.ROUND_HALF_UP);

if(discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;

return discountAmount;

}

}

直接减规则

public class ZjCouponDiscount implements ICouponDiscount<Double> {

@Override

public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

BigDecimal discountAmount = skuPrice.subtract(new BigDecimal(couponInfo));

if(discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;

return discountAmount;

}

}

3、策略上下文

        定义策略的上下文,策略控制器,通过控制器调用不同的优惠策略

public class Context <T>{

private ICouponDiscount<T> couponDiscount;

public Context(ICouponDiscount<T> couponDiscount) {

this.couponDiscount = couponDiscount;

}

public BigDecimal discountAmount(T couponInfo,BigDecimal skuPrice){

return couponDiscount.discountAmount(couponInfo,skuPrice);

}

}

4、编写测试类(调用方法)

        调用控制器,走不同的折扣规则

@Test

public void test(){

Context<Double> context = new Context<Double>(new ZJCouponDiscount());

BigDecimal discountAmount = context.discountAmount(10D, new BigDecimal(100));

logger.info("测试结果:直减优惠后金额 {}", discountAmount);

}

网址:十分钟利用springboot写电商支持多种优惠券规则,使用策略模式替代大量的if https://www.yuejiaxmz.com/news/view/312337

相关内容

重学 Java 设计模式:实战策略模式「模拟多种营销类型优惠券,折扣金额计算策略场景」
策略模式(Strategy Pattern):电商平台的优惠券系统实战案例分析
优惠券的最佳利用策略:如何在Java代码中优化优惠券的使用
如何有效使用优惠券以节省开支?这些使用策略有哪些限制和条件?
【设计模式】策略模式 ( 简介
10 个优惠券营销策略技巧(销量猛增)
优惠券使用攻略:省钱秘籍一网打尽!
关于订单的多件折扣及优惠券实现设计模式(组合+策略模式)
C++ 设计模式之策略模式
优惠券管理策略:提高营销效果的关键

随便看看