关于解决多个ifelse的探索(一)

/**
 * 参考如下
 * https://zhuanlan.zhihu.com/p/157793899
 */
public class Test1 {
    static Map<String, Consumer<String>> actionMappings = new HashMap<>();
    public static void main(String[] args) {
        actionMappings.put("value1", Test1::method1);
        actionMappings.put("value2", Test1::method2);
        actionMappings.put("value3", Test1::method3);


        // 有如下代码扩展性太差,需重构
        extracted_1("value2");
        System.out.println("===================================");
        extracted_2("value3");
        extracted_2("s");
    }

    private static void extracted_2(String param) {
        // 重构后的 ifelse在有限调用时,只需要
        actionMappings.getOrDefault(param, Test1::defaultMethod).accept(param);
    }

    private static void defaultMethod(String i) {
        System.out.println("this is defaultMethod");
    }

    private static void extracted_1(String param) {
        if ("value1".equals(param)) {
            method1(param);
        } else if ("value2".equals(param)) {
            method2(param);
        } else if ("value3".equals(param)) {
            method3(param);
        }
    }

    private static void method1(String i) {
        System.out.println("this is method1");
    }

    private static void method2(String i) {
        System.out.println("this is method2");
    }

    private static void method3(String i) {
        System.out.println("this is method3");
    }

}
posted @ 2022-05-28 15:53  夜旦  阅读(33)  评论(0编辑  收藏  举报