目录
使用背景: 笔者遇到促销活动中,需要使用优惠券的功能,由于优惠券的使用条件是随着季节的变化而变化的,所以在进行编码时,为了遵循 可扩展,抽象变化的 原则,进行了责任链的模式的实践,
使用条件
1.授信金额 在 2000~ 4000 ,
2.订单金额在 3000~3500,
3.分期期数在 2~6
………
明显这些 条件不可能穷举,而且还会随着时间而增加,
抽象出公共部分
1.为了 显的高逼格抽象类 是不可缺少的
public interface PromotionHandler {
public ResultData judgeIegal();
}
2.抽象类 里面可以放置一些公共的方法
public abstract class PromotionHandlerAbs {
private PromotionHandler promotionHandler;
public PromotionHandler getPromotionHandler() {
return promotionHandler;
}
public void setPromotionHandler(PromotionHandler promotionHandler) {
this.promotionHandler = promotionHandler;
}
public static boolean getBooleanBystr(String str1) {
if (!Strings.isNullOrEmpty(str1))
{ return true; } else { return false; }
}
}
- 变化的具体实现类 (肯定是多个,如果以后需要添加,其实可以随意扩展,或者在原有基础上进行兼容)
@Getter @Setter
public class PromotionHandlerOverDue extends PromotionHandlerAbs implements PromotionHandler {
private Date startTme;
private Date nowTme;
private Date judgeTme;
public PromotionHandlerOverDue() { }
public PromotionHandlerOverDue(Date startTme, Date nowTme, Date judgeTme) {
this.startTme = startTme;
this.nowTme = nowTme;
this.judgeTme = judgeTme;
}
@Override
public ResultData judgeIegal() {
ResultData resultData = new ResultData(false, null);
if (this.judgeTme != null) {
String judgeDateFmt = DateUtils.formatStr6Date(this.judgeTme, DateUtils.DATE_PATTON_1);
String nowDateFmt = DateUtils.formatStr6Date(this.nowTme, DateUtils.DATE_PATTON_1);
if (judgeDateFmt.compareTo(nowDateFmt) >= 0) {
if (getPromotionHandler() != null) {
return getPromotionHandler().judgeIegal();
} else {
resultData.setFlag(true);
return resultData;
}
} else {
resultData.setData("该优惠券已经过期");
return resultData;
}
} else {
resultData.setData("该优惠券没有设置过期时间");
return resultData;
}
}
}
具体的使用
先 构造链条 a.set(B),b.set(c) ———-> a.judge();
PromotionHandlerOverDue promotionHandlerOverDue = new PromotionHandlerOverDue(tPromotionUsingInfo.getStartUsingTime(),
new Date(), tPromotionUsingInfo.getEndUsingTime());
//判断 申请期数是否符合 min_period
PromotionHandlerPeriod promotionHandlerPeriod = new PromotionHandlerPeriod(applyMsg.getApplyPeriod(),
sourceModel.getMinPeriod(), sourceModel.getMaxPeriod(), sourceModel.getMaxPeriodSybol(), sourceModel.getMinPeriodSybol());
//判断 订单金额是否符合 min_amount
PromotionHandlerAmount promotionHandlerAmount = new PromotionHandlerAmount(applyMsg.getApplyAmount(),
promotionHandlerPeriod.setPromotionHandler(promotionHandlerAmount); promotionHandlerAmount.setPromotionHandler(promotionHandlerOverDue);
ResultData resultData = promotionHandlerPeriod.judgeIegal();