@Service
public class BizService {
@Autowired
private BizUnitService service;
private Map<Integer, Function<String, String>> map= new HashMap<>();
/**
* 初始化 业务逻辑分派Map 其中value 存放的是 lambda表达式
* 当bean创建完成的时候,会后置执行@PostConstruct
* 加载bean的时候会直接把方法添加到map里面
*/
@PostConstruct
public void checkResultDispatcherMuitInit() {
map.put(1, order -> service.bizOne(order));
map.put(2, order -> service.bizTwo(order));
map.put(3, order -> service.bizThree(order));
}
public String getCheckResultMuti(String order, Integer level) {
Function<String, String> result = map.get(level);
if (result != null) {
//执行这段表达式获得String类型的结果
return result.apply(order);
}
return "不在处理的逻辑中返回业务错误";
}
@Service
public class BizUnitService {
public String bizOne(String order) {
return order + "各种花式操作1";
}
public String bizTwo(String order) {
return order + "各种花式操作2";
}
public String bizThree(String order) {
return order + "各种花式操作3";
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestClass {
@Autowired
private BizService bizService;
/**
* 使用策略模式优化if else
* */
@Test
public void method(){
System.out.println( bizService.getCheckResultMuti("嗯哼--", 1));
}
}
看下打印