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";
    }
}
复制代码

 

posted @   蔡徐坤1987  阅读(210)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示