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內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: