1. 程式人生 > 其它 >關於解決多個ifelse的探索(一)

關於解決多個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");
    }

}