最近有一个需求,很简单,但是代码写起来很难看,也不够优雅,后来发现lambda表达式中有一个Function函数,根据优惠券的类型resourceType和编码resourceId来 查询发放方式grantType和领取规则
先看看我最初的实现方式:
- 根据优惠券类型resourceType -> 确定查询哪个数据表
- 根据编码resourceId -> 到对应的数据表里边查询优惠券的派发方式grantType和领取规则
优惠券大致有以下几种:
- 红包 —— 红包发放规则表
- 购物券 —— 购物券表
- QQ会员
- 外卖会员
我第一次的思路是通过若干个if-else进行查询:
switch(resourceType){
case "红包":
查询红包的派发方式
break;
case "购物券":
查询购物券的派发方式
break;
case "QQ会员" :
break;
case "外卖会员" :
break;
......
default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
break;
}
这样写扩展性几乎就是没有,也就是说在来几种优惠券的话,只能改了代码重新上线才行,不够灵活,而且不易维护,后来又想到策略模式,因为策略模式的设计原则就是把会变化的部分抽取并封装起来,这样就可以保证其他部分不受影响,这样做的好处是代码变化引起的不经意后果变少,而且系统也会变得更有弹性。
于是我的代码变成了
这样的话我们就把变化的部分即红包和购物券等这种封装起来,当我们需要什么类型的优惠券或者红包就去调用即可,虽然最后还是需要判断是红包,还是优惠券或者会员等,但是我们后面维护的时候就会及其的容易
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;
虽然我已经将变化的利用策略模式封装起来,但缺点也明显:
- 如果 if-else的判断情况很多,那么对应的具体策略实现类也会很多,上边的具体的策略实现类还只是2个,查询红包发放方式写在类RedPaper里边,购物券写在另一个类Shopping里边;那资源类型多个QQ会员和外卖会员,不就得再多写两个类?有点麻烦了
- 没法俯视整个分派的业务逻辑
Map+函数式接口
我们利用Java8的新特性lambda表达式:
- 判断条件放在key中
- 对应的业务逻辑放在value中
这样子写的好处是非常直观,能直接看到判断条件对应的业务逻辑
接下来我们继续实现上面的需求,即:
根据优惠券(资源)类型resourceType和编码resourceId查询派发方式grantType
public interface GrantTypeSerive {
public String redPaper(String resourceId);
public String shopping(String resourceId);
public String QQVip(String resourceId);
}
public interface QueryGrantTypeService {
void dispatcherInit();
String getResult(String resourceType);
}
@Service
public class GrantTypeSeriveImpl implements GrantTypeSerive {
@Override
public String redPaper(String resourceId) {
//红包的发放方式
return "每周末9点发放";
}
@Override
public String shopping(String resourceId) {
//购物券的发放方式
return "每周三9点发放";
}
@Override
public String QQVip(String resourceId) {
//qq会员的发放方式
return "每周一0点开始秒杀";
}
}
注意:里面有个参数是resourceId,原本是用于调用数据库的,但是我没有调用,本文功能旨在突出Function函数表达式的用法,所以直接返回了一个字符串。
import com.example.mapfunction.service.GrantTypeSerive;
import com.example.mapfunction.service.QueryGrantTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class QueryGrantTypeServiceImpl implements QueryGrantTypeService {
@Autowired
private GrantTypeSerive grantTypeSerive;
private Map> grantTypeMap = new HashMap<>();
@Override
@PostConstruct
public void dispatcherInit() {
grantTypeMap.put("红包", resourceId -> grantTypeSerive.redPaper(resourceId));
grantTypeMap.put("购物券", resourceId -> grantTypeSerive.shopping(resourceId));
grantTypeMap.put("qq会员", resourceId -> grantTypeSerive.QQVip(resourceId));
}
@Override
public String getResult(String resourceType) {
//Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
Function result = grantTypeMap.get(resourceType);
if (result != null) {
//传入resourceId 执行这段表达式获得String型的grantType
return result.apply(resourceType);
}
return "查询不到该优惠券的发放方式";
}
}
上面用到了一个注解:@PostConstruct,这个注解作用很大,我简单的说一下:
@PostConstruct是 Spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在Spring容器初始化的时候执行该方法。
从javaEE5规范开始,Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。
@PostConstruct注解的方法在项目启动时执行,即Spring容器启动时执行,可做一些数据常规化加载,比如:数据字典之类的。
执行顺序:
其实从依赖注入的字面意思就可以知道,要将对象p注入到对象a,那么首先就必须得生成对象a和对象p,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
Constructor >>@Autowired >> @PostConstruct
接下来简单的进行一个测试:
import com.example.mapfunction.service.QueryGrantTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GrantTypeController {
@Autowired
private QueryGrantTypeService queryGrantTypeService;
@GetMapping("/grantType/{resourceName}")
public String test(@PathVariable String resourceName) {
return queryGrantTypeService.getResult(resourceName);
}
}
总结:
策略模式通过接口、实现类、逻辑分派来完成,把 if语句块的逻辑抽出来写成一个类,更好维护。
Map+函数式接口通过Map.get(key)来代替 if-else的业务分派,能够避免策略模式带来的类增多、难以俯视整个业务逻辑的问题。



