闽公网安备 35020302035485号
switch(resourceType){
case "红包":
查询红包的派发方式
break;
case "购物券":
查询购物券的派发方式
break;
case "QQ会员" :
break;
case "外卖会员" :
break;
......
default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
break;
}
如果要这么写的话, 一个方法的代码可就太长了,影响了可读性。(别看着上面case里面只有一句话,但实际情况是有很多行的)。而且由于 整个 if-else的代码有很多行,也不方便修改,可维护性低。switch(resourceType){
case "红包":
String grantType=new Context(new RedPaper()).ContextInterface();
break;
case "购物券":
String grantType=new Context(new Shopping()).ContextInterface();
break;
......
default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
break;
但缺点也明显:@Service
public class QueryGrantTypeService {
@Autowired
private GrantTypeSerive grantTypeSerive;
private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();
/**
* 堆代码 duidaima.com
* 初始化业务分派逻辑,代替了if-else部分
* key: 优惠券类型
* value: lambda表达式,最终会获得该优惠券的发放方式
*/
@PostConstruct
public void dispatcherInit(){
grantTypeMap.put("红包",resourceId->grantTypeSerive.redPaper(resourceId));
grantTypeMap.put("购物券",resourceId->grantTypeSerive.shopping(resourceId));
grantTypeMap.put("qq会员",resourceId->grantTypeSerive.QQVip(resourceId));
}
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(resourceId);
}
return "查询不到该优惠券的发放方式";
}
}
如果单个 if 语句块的业务逻辑有很多行的话,我们可以把这些 业务操作抽出来,写成一个单独的Service,即://具体的逻辑操作
@Service
public class GrantTypeSerive {
public String redPaper(String resourceId){
//红包的发放方式
return "每周末9点发放";
}
public String shopping(String resourceId){
//购物券的发放方式
return "每周三9点发放";
}
public String QQVip(String resourceId){
//qq会员的发放方式
return "每周一0点开始秒杀";
}
}
入参String resourceId是用来查数据库的,这里简化了,传参之后不做处理。@RestController
public class GrantTypeController {
@Autowired
private QueryGrantTypeService queryGrantTypeService;
@PostMapping("/grantType")
public String test(String resourceName){
return queryGrantTypeService.getResult(resourceName);
}
}

你的队友得会lambda表达式才行啊,他不会让他自己百度去