Java代替if和switch的方法(記錄一下)


package xcc.mapTest;

/**
 * @Decription: 接口
 * @Author:
 * @Date:
 * @Email:
 **/
public interface Function {

    /**
     * 要做的事情
     */
    void invoke();
}
package xcc.mapTest;

import java.util.Map;

/**
 * @Decription: 代替'if else' 和 'switch'的方法
 * @Author:
 * @Date:
 * @Email:
 **/
public class IfFunction<K> {

    private Map<K, Function> map;

    /**
     *  通過map類型來保存對應的條件key和方法
     *
     * @param map a map
     */
    public IfFunction(Map<K, Function> map) {
        this.map = map;
    }

    /**
     * 添加條件
     *
     * @param key      需要驗證的條件(key)
     * @param function 要執行的方法
     * @return this.
     */
    public IfFunction<K> add(K key, Function function) {
        this.map.put(key, function);
        return this;
    }

    /**
     * 確定key是否存在,如果存在,則執行相應的方法。
     *
     * @param key the key need to verify
     */
    public void doIf(K key) {
        if (this.map.containsKey(key)) {
            map.get(key).invoke();
        }
    }

    /**
     * 確定key是否存在,如果存在,則執行相應的方法。
     * 否則將執行默認方法
     *
     * @param key             需要驗證的條件(key)
     * @param defaultFunction 要執行的方法
     */
    public void doIfWithDefault(K key, Function defaultFunction) {
        if (this.map.containsKey(key)) {
            map.get(key).invoke();
        } else {
            defaultFunction.invoke();
        }
    }

}
package xcc.mapTest;

import java.util.HashMap;

public class Test3 {
    public static void main(String[] args) {
        IfFunction<String> ifFunction = new IfFunction<>(new HashMap<>(5));

        //定義好要判斷的條件和對應執行的方法
        ifFunction.add("1", () -> System.out.println("蘋果"))
                .add("2", () -> System.out.println("西瓜"))
                .add("3", () -> System.out.println("橙子"));

        //要進入的條件
        ifFunction.doIf("2");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM