if,else太多使用策略模式解决
TestController
@RestController("TestController") @RequestMapping("/test") public class TestController { @Autowired private TestService testService; private Map<String, Function<String, String>> resultMap = Maps.newConcurrentMap(); @PostConstruct public void init() { resultMap.put("1", type -> testService.handler1(type)); resultMap.put("2", type -> testService.handler2(type)); resultMap.put("3", type -> testService.handler3(type)); resultMap.put("4", type -> testService.handler4(type)); } @RequestMapping(value = "/listByType2", method = RequestMethod.GET) public String listByType2(@RequestParam(value = "type") String type) { Function<String, String> function = resultMap.get(type); if (function == null) { return null; } return function.apply(type); } //正常写法 @RequestMapping(value = "/listByType", method = RequestMethod.GET) public String listByType(@RequestParam(value = "type") String type) { if (type.equals("1")) { return testService.handler1(type); } else if (type.equals("2")) { return testService.handler2(type); } else if (type.equals("3")) { return testService.handler3(type); } else if (type.equals("4")) { return testService.handler4(type); } return "执行其他函数0"; } }
TestService
public interface TestService { String handler1(String type); String handler2(String type); String handler3(String type); String handler4(String type); }
TestServiceImpl
@Service("TestService") public class TestServiceImpl implements TestService{ @Override public String handler1(String type) { return "执行逻辑方法1"; } @Override public String handler2(String type) { return "执行逻辑方法2"; } @Override public String handler3(String type) { return "执行逻辑方法3"; } @Override public String handler4(String type) { return "执行逻辑方法4"; } }