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可以將一組實現(xiàn)了同樣接口的類注入一個List
/*** * 定義接口。type用來路由具體的Handler實現(xiàn) * */ public interface Handler { String getType(); void execute(); } /** * 將Handler接口的實現(xiàn)類注入一個List * */ @Autowired private List<Handler> handlerList; @Test public void testAutowireList(){ // 根據(jù)類型判斷該由哪個具體實現(xiàn)類處理 for(Handler handler:handlerList){ if(input.equals(handler.getType())){ handler.execute(); } } }
下面是幾種輕量級實現(xiàn).
2. 反射
通過反射動態(tài)調(diào)用相應的方法
/*** *定義每種類型所對應的方法 */ 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"); } } /*** * * 通過反射,動態(tài)調(diào)用方法。采用了Guava的工具類。 * */ @Test public void testReflect() throws Exception { //首字母大寫,根據(jù)類型拼接方法 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表達式
實現(xiàn)同上面的反射,結合了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. 枚舉
在枚舉里面定義一個抽象方法,每種類型對應各自的具體實現(xiàn)。
/** * 定義枚舉類,包含了所有類型 */ 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內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java之next()、nextLine()區(qū)別及問題解決
這篇文章主要介紹了Java之next()、nextLine()區(qū)別及問題解決,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08SpringCloud-Hystrix實現(xiàn)原理總結
通過hystrix可以解決雪崩效應問題,它提供了資源隔離、降級機制、融斷、緩存等功能。接下來通過本文給大家分享SpringCloud-Hystrix實現(xiàn)原理,感興趣的朋友一起看看吧2021-05-05