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"; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?