策略模式 - 实现优惠券
2022-07-07 本文已影响0人
kacen
这次比较简单粗暴哈,先按照下图来创建相对应的类和方法吧。
截屏2022-07-08 上午11.23.14.png 截屏2022-07-08 上午11.23.30.png
截屏2022-07-08 上午11.23.54.png
截屏2022-07-08 上午11.24.20.png
CouponStrategyContext.java
@Data
@AllArgsConstructor
@Component
@Slf4j
public class CouponStrategyContext implements ApplicationContextAware {
/**
* 优惠券策略类集合
*/
private static Map<String, CouponStrategy> couponStrategyMap;
/**
* 策略上下文对象委派具体的策略执行算法
*
* @param couponDTO
* @return
*/
public static Object couponHandler(CouponDTO couponDTO) {
return getCouponStrategy(couponDTO.getCouponTypeEnum()).couponHandler(couponDTO);
}
/**
* 获取适用的策略处理类
*
* @param couponType
* @return
*/
private static CouponStrategy getCouponStrategy(CouponTypeEnum couponType) {
return Optional.ofNullable(couponStrategyMap.get(couponType.name()))
.orElseThrow(() -> new RuntimeException(String.format("not found coupon type strategy , coupon type is %s", couponType.name())));
}
/**
* 从容器中加载所有优惠券策略接口的实现类,注册到优惠券策略集合中
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, CouponStrategy> strategyBeans = applicationContext.getBeansOfType(CouponStrategy.class);
if (strategyBeans == null || strategyBeans.size() == 0) {
// 无可用的优惠券策略
log.info("无可用的优惠券策略");
return;
}
log.info("预加载优惠策略集合Map,一共有"+strategyBeans.size()+"策略");
couponStrategyMap = new HashMap<>(strategyBeans.size());
for (CouponStrategy strategy : strategyBeans.values()) {
couponStrategyMap.put(strategy.applyCouponType().name(), strategy);
log.info("register strategy " + strategy.applyCouponType());
}
log.info("加载完毕 - couponStrategyMap{}",couponStrategyMap);
}
}
CouponStrategyContext是唯一一个有代码的哈,可以自行参考具体的实现哈。
最后测试一下
CouponDTO couponDTO = new CouponDTO();
couponDTO.setCouponTypeEnum(CouponTypeEnum.DiscountCoupon);
Object o = CouponStrategyContext.couponHandler(couponDTO);