1. 程式人生 > 程式設計 >Java中避免過多if-else的幾種方法

Java中避免過多if-else的幾種方法

太多的if-else不太直觀,難以維護。

以下面程式碼為例,展示幾種替代if else的方法。

String input = "three";

  @Test
  public void testElse() {
    if ("one".equals(input)) {
      System.out.println("one");
    } else if ("two".equals(input)) {
      System.out.println("two");
    } else if ("three".equals(input)) {
      System.out.println("three");
    } else if ("four".equals(input)) {
      System.out.println("four");
    }
  } 

需要引入Spring跟Guava依賴

1.Spring結合策略模式

Spring可以將一組實現了同樣介面的類注入一個List

/***
 * 定義介面。type用來路由具體的Handler實現
 * */
public interface Handler {
  String getType();

  void execute();
}
 /**
   * 將Handler介面的實現類注入一個List
   * */
  @Autowired
  private List<Handler> handlerList;
  @Test
  public void testAutowireList(){
  // 根據型別判斷該由哪個具體實現類處理
     for(Handler handler:handlerList){
       if(input.equals(handler.getType())){
         handler.execute();
       }
     }
  } 

下面是幾種輕量級實現.

2. 反射

通過反射動態呼叫相應的方法

/***
 *定義每種型別所對應的方法
*/
public class ReflectTest {
  public void methodOne() {
    System.out.println("one");
  }

  public void methodTwo() {
    System.out.println("two");
  }

  public void methodThree() {
    System.out.println("three");
  }

  public void methodFour() {
    System.out.println("four");
  }

}

 /***
   *
   * 通過反射,動態呼叫方法。採用了Guava的工具類。
   * */
  @Test
  public void testReflect() throws Exception {
    //首字母大寫,根據型別拼接方法
    String methodName = "method" + LOWER_CAMEL.to(UPPER_CAMEL,input);
    Method method = ReflectTest.class.getDeclaredMethod(methodName);
    Invokable<ReflectTest,Object> invokable =
        (Invokable<ReflectTest,Object>) Invokable.from(method);
    invokable.invoke(new ReflectTest());
  } 

3. lambda表示式

實現同上面的反射,結合了Java 8的新特性:lambda表示式

  @Test
  public void testJava8() {
    Map<String,Consumer<ReflectTest>> functionMap = Maps.newHashMap();
    functionMap.put("one",ReflectTest::methodOne);
    functionMap.put("two",ReflectTest::methodTwo);
    functionMap.put("three",ReflectTest::methodThree);
    functionMap.put("four",ReflectTest::methodThree);
    functionMap.get(input).accept(new ReflectTest());
  } 

4. 列舉

在列舉裡面定義一個抽象方法,每種型別對應各自的具體實現。

/**
 * 定義列舉類,包含了所有型別
 */
public enum EnumTest {


  ONE("one") {
    @Override
    public void apply() {
      System.out.println("one");
    }
  },TWO("two") {
    @Override
    public void apply() {
      System.out.println("two");
    }
  },THREE("three") {
    @Override
    public void apply() {
      System.out.println("three");
    }
  },FOUR("four") {
    @Override
    public void apply() {
      System.out.println("four");
    }
  };

  public abstract void apply();

  private String type;

  EnumTest(String type) {
    this.type = type;
  }

  public String getType() {
    return type;
  }

}
 // 列舉測試
 @Test
  public void testEnum() {
    EnumTest.valueOf(input.toUpperCase()).apply();
  }

到此這篇關於Java中避免過多if-else的幾種方法的文章就介紹到這了,更多相關Java 過多if-else內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!