1、策略者模式
策略者模式 不懂就看
菜鸟教程
应用场景:列入支付方式很多种,优惠卷多种策略,考试组卷策略等等
优惠卷:有商家优惠卷,有平台优惠卷等
这样不适用策略者模式的话会显得 巴拉巴拉很多影响了可读性 也不方便修改,可维护性低
switch(resourceType){
case "优惠卷类型1":
//优惠的逻辑
break;
case "优惠卷类型2":
//优惠的逻辑
break;
case "优惠卷类型3" :
//优惠的逻辑
break;
case "优惠卷类型4" :
break;
......
default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
break;
}
使用策略模式
switch(resourceType){
case "优惠卷类型1":
String grantType=new Context(new RedPaper()).ContextInterface();
break;
..........等
2、Map+函数式接口
@Autowired
//优惠卷处理路哟及
private TypeSerive typeSerive;
private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();
/**
* 初始化业务分派逻辑,代替了if-else部分
* key: 优惠券类型
* value: lambda表达式,最终会获得该优惠券的发放方式
*/
@PostConstruct
public void dispatcherInit(){
grantTypeMap.put("优惠卷类型1",resourceId->typeSerive.type1());
grantTypeMap.put("优惠卷类型2",resourceId->typeSerive.type2());
}
public String getResult(String resourceType){
//Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
Function<String,String> result=getGrantTypeMap.get(resourceType);
if(result!=null){
//传入resourceId 执行这段表达式获得String型的grantType
return result.apply();
}
return "查询不到该优惠券的发放方式";
}
@Service
public class TypeSerive {
public String type1(){
return "type1";
}
public String type2(){
//购物券的发放方式
return "type2";
}
}
使用
getResult("优惠卷类型1")