Java用什么来代替If else 和switch

在Java中,偶尔会遇到这样的情况:有很多条件需要判断,而且满足每个条件需要做的事情也不一样。在写代码时第一想法肯定是if...else了,可当代码写出来后,会发现很长一串的if,else if,代码很难看,如果当前的条件是最后一次才满足条件,那么程序需要去检查每一个if里的条件是否满足,这样似乎还会影响程序性能。

    那么用什么来代替呢,很多人肯定可能会想到,肯定是switch了。网上有很多switch与if else的评论,也有将二者的性能拿出来做比较的,而在我现在工作的公司,不允许在判断条件多的时候是用if else,更不能用switch代替if else。那究竟该怎么办?于是在网上找了许久答案,终于有了个方向。用map代替,map的key代表需要判断的条件,而value则是满足条件时需要去干的事儿。于是,我照着自己的想法写了如下一个关于if的工具类。

package com.asen.util;

import java.util.Map;

/**
 * @Decription: a function,can replace the 'if else' and 'switch'
 * @Author: Asen
 * @Date: Create in 16:36 2018/4/29 0029
 * @Email: [email protected]
 **/
public class IfFunction<K> {
   
   private Map<K, Function> map;
   
   /**
    * the IfFunction need a map to save keys and functions
    *
    * @param map a map
    */
   public IfFunction(Map<K, Function> map) {
      this.map = map;
   }
   
   /**
    * add key and function to the map
    *
    * @param key      the key need to verify
    * @param function it will be executed when the key exists
    * @return this.
    */
   public IfFunction<K> add(K key, Function function) {
      this.map.put(key, function);
      return this;
   }
   
   /**
    * Determine whether the key exists, and if there is, the corresponding method is executed.
    *
    * @param key the key need to verify
    */
   public void doIf(K key) {
      if (this.map.containsKey(key)) {
         map.get(key).invoke();
      }
   }
   
   /**
    * Determine whether the key exists, and if there is, the corresponding method is executed.
    * otherwise the defaultFunction is executed.
    *
    * @param key             the key need to verify
    * @param defaultFunction it will be executed when the key is not exists.
    */
   public void doIfWithDefault(K key, Function defaultFunction) {
      if (this.map.containsKey(key)) {
         map.get(key).invoke();
      } else {
         defaultFunction.invoke();
      }
   }
   
}
package com.asen.util;

/**
 * @Decription: the function of IfFunction's key
 * @Author: Asen
 * @Date: Create in 17:35 2018/4/29 0029
 * @Email: [email protected]
 **/
public interface Function {
   
   /**
    * need to do something
    */
   void invoke();
}
package com.asen.example;

import com.asen.util.IfFunction;

import java.util.HashMap;

/**
 * @Decription: the IfFunction test
 * @Author: Asen
 * @Date: Create in 12:39 2018/5/1 0001
 * @Email: [email protected]
 **/
public class Test {
   
   public static void main(String[] args) {
      
      IfFunction ifFunction = new IfFunction<>(new HashMap<>(5));
      
      ifFunction.add("hello", () -> System.out.println("你好"))
            .add("helloWorld", () -> System.out.println("你好,世界"))
            .doIfWithDefault("hello", () -> System.out.println("没有找到对应的key!"));
   }
}


自己用起来感觉还不错,就是不知道性能怎么样。没有做过什么测试!

项目源代码地址:https://github.com/SmythAsen/if-util



你可能感兴趣的:(Java)