策略模式

1.策略模式简介

1.策略模式是⼀种⾏为模式,也是替代⼤量 ifelse 的利器。
2.应用场景:具有同类可替代的⾏为逻辑算法场景

2.1 不同类型的交易⽅式(信⽤卡、⽀付宝、微信)
2.2 不同的抽奖策略(必中抽奖概率方式、单项抽奖方式)

2.案例场景

我们模拟在购买商品时候使⽤的各种类型优惠券(满减、直减、折扣、n元购)

3.普通代码实现

以下代码在CouponDiscountService.java

public class CouponDiscountService {
 public double discountAmount(int type, double typeContent, double
skuPrice, double typeExt) {
 // 1. 直减券
 if (1 == type) {
 return skuPrice - typeContent;
 }
 // 2. 满减券
 if (2 == type) {
 if (skuPrice < typeExt) return skuPrice;
 return skuPrice - typeContent;
 }
 // 3. 折扣券
 if (3 == type) {
 return skuPrice * typeContent;
 }
 // 4. n元购
 if (4 == type) {
 return typeContent;
 }
 return 0D;
 }
}

分析

1.不同的优惠券类型可能需要不同的入口参数,比如直减券不需要知道商品金额,满减券需要知道商品金额,造成了入口参数的增加,不能由入口参数去判断某种优惠券需要哪些条件。
2.随着产品功能的增加,需要不断扩展if语句,代码可读性差。

4.策略模式结构模型

4.1 工程结构

4.2 策略模式结构分析

1.定义了优惠券接口,增加了泛型用于不同类型的接口传递不同的类型参数。

public interface ICouponDiscount<T> {
 /**
 * 优惠券⾦额计算
 * @param couponInfo 券折扣信息;直减、满减、折扣、N元购
 * @param skuPrice sku⾦额
 * @return 优惠后⾦额
 */
 BigDecimal discountAmount(T couponInfo, BigDecimal skuPrice);
}

2.具体的优惠券行为去实现优惠券接口类,实现自己的优惠券策略。
3.增加了策略控制类Context,使外部通过统一的方法执行不同的优惠策略计算。

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);
 }
}
posted @ 2022-05-05 19:25  盐小果  阅读(96)  评论(0编辑  收藏  举报