提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
java8 lambda function函数来替换if else:
但是方法实现过多 还是建议策略模式
提示:简单demo,下面案例可供参考
相关代码
@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
//创建map并 初始化映射关系
private static Map<String, Function<Map<String, Object>, Integer>> dispatcher = Maps.newHashMap();
//定义方法的类型 if else的条件
private static String TYPE_ONE = "one";
private static String TYPE_TWO = "two";
private static String TYPE_THR = "thr";
@PostConstruct
public void initDispatcher() {
dispatcher.put(TYPE_ONE, this::methodOne);
dispatcher.put(TYPE_TWO, this::methodTwo);
dispatcher.put(TYPE_THR, this::methodThr);
}
//入参map也可以替换为Vo
public Integer methodOne(Map<String, Object> map) {
log.info("methodOne,map:{}", JacksonUtil.mapToJson(map));
return 1;
}
public Integer methodTwo(Map<String, Object> map) {
log.info("methodTwo,map:{}", JacksonUtil.mapToJson(map));
return 2;
}
public Integer methodThr(Map<String, Object> map) {
log.info("methodThr,map:{}", JacksonUtil.mapToJson(map));
return 3;
}
//使用方法
public Integer test() {
//type相当于if条件 或者switch 中case条件
String type = TYPE_ONE;
//获取对应的方法
Function<Map<String, Object>, Integer> mapIntegerFunction = dispatcher.get(type);
//参数组装
Map<String, Object> map = new HashMap<>();
map.put("param","test");
map.put("param2","test2");
//执行方法
Integer apply = mapIntegerFunction.apply(map);
log.info("测试结果,apply:{}",apply);
return apply;
}
使用方法
@RequestMapping("/testlambda")
public Integer test() {
String type = TYPE_ONE;
Function<Map<String, Object>, Integer> mapIntegerFunction = dispatcher.get(type);
Map<String, Object> map = new HashMap<>();
map.put("param","test");
map.put("param2","test2");
Integer apply = mapIntegerFunction.apply(map);
System.out.println(apply);
return apply;
}
测试方法执行结果
总结
简单的java8 lambda function函数来替换if else代码demo