您好,登錄后才能下訂單哦!
這篇文章主要講解了java消除大量的if else判斷的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
1.簡介
if判斷語句是很多編程語言的重要組成部分。但是,若我們最終編寫了大量嵌套的if語句,這將使得我們的代碼更加復雜和難以維護。
讓我們看看能否使用別的方式來做呢。
設計模式是為了更好的代碼重用性,可讀性,可靠性,可維護性,它有六大原則:
2.示例if..else
public int calculate(int a, int b, String operator) { int result = Integer.MIN_VALUE; if ("add".equals(operator)) { result = a + b; } else if ("multiply".equals(operator)) { result = a * b; } else if ("divide".equals(operator)) { result = a / b; } else if ("subtract".equals(operator)) { result = a - b; } else if ("modulo".equals(operator)) { result = a % b; } return result; }
switch-case
public int calculateUsingSwitch(int a, int b, String operator) { int result = 0; switch (operator) { case "add": result = a + b; break; case "multiply": result = a * b; break; case "divide": result = a / b; break; case "subtract": result = a - b; break; case "modulo": result = a % b; break; default: result = Integer.MIN_VALUE; } return result; }
3.重構
3.1 工廠方式重構
抽象層Operation.java
public interface Operation { int apply(int a, int b); }
加法實現Addition.java:
public class Addition implements Operation { @Override public int apply(int a, int b) { return a + b; } }
減法實現Subtraction.java
public class Subtraction implements Operation { @Override public int apply(int a, int b) { return a - b; } }
乘法實現Multiplication.java
public class Multiplication implements Operation { @Override public int apply(int a, int b) { return a\*b; } }
除法實現Division.java
public class Division implements Operation { @Override public int apply(int a, int b) { return a / b; } }
求余實現Modulo.java
public class Modulo implements Operation { @Override public int apply(int a, int b) { return a % b; } }
工廠類OperatorFactory.java
import java.util.HashMap; import java.util.Map; import java.util.Optional; public class OperatorFactory { static Map<String, Operation> operationMap = new HashMap<>(); static { operationMap.put("add", new Addition()); operationMap.put("divide", new Division()); operationMap.put("multiply", new Multiplication()); operationMap.put("subtract", new Subtraction()); operationMap.put("modulo", new Modulo()); } public static Optional<Operation> getOperation(String operation) { return Optional.ofNullable(operationMap.get(operation)); } }
使用示例
public int calculateUsingFactory(int a, int b, String operator) { Operation targetOperation = OperatorFactory .getOperation(operator) .orElseThrow(() -> new IllegalArgumentException("Invalid Operator")); return targetOperation.apply(a, b); }
3.2 枚舉方式重構
枚舉實現Operator.java
public enum Operator { ADD { @Override public int apply(int a, int b) { return a + b; } }, MULTIPLY { @Override public int apply(int a, int b) { return a * b; } }, SUBTRACT { @Override public int apply(int a, int b) { return a - b; } }, DIVIDE { @Override public int apply(int a, int b) { return a / b; } }, MODULO { @Override public int apply(int a, int b) { return a % b; } }; public abstract int apply(int a, int b); }
封裝Operator到Calculator.java
public int calculate(int a, int b, Operator operator) { return operator.apply(a, b); }
使用示例
@Test public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() { Calculator calculator = new Calculator(); int result = calculator.calculate(3, 4, Operator.valueOf("ADD")); assertEquals(7, result); }
3.3 命令模式
抽象的接口
public interface Command { Integer execute(); }
實現類
package com.baeldung.reducingIfElse; public class AddCommand implements Command { private int a; private int b; public AddCommand(int a, int b) { this.a = a; this.b = b; } @Override public Integer execute() { return a + b; } }
其它略
包裝
public int calculate(Command command) { return command.execute(); }
測試demo
@Test public void whenCalculateUsingCommand_thenReturnCorrectResult() { Calculator calculator = new Calculator(); int result = calculator.calculate(new AddCommand(3, 7)); assertEquals(10, result); }
3.4 規則引擎重構
抽象規則
public interface Rule { boolean evaluate(Expression expression); Result getResult(); }
實現規則AddRule.java 其它略
public class AddRule implements Rule { private int result; @Override public boolean evaluate(Expression expression) { boolean evalResult = false; if (expression.getOperator() == Operator.ADD) { this.result = expression.getX() + expression.getY(); evalResult = true; } return evalResult; } @Override public Result getResult() { return new Result(result); } }
其中:返回結果
public class Result { int value; public Result(int value) { this.value = value; } public int getValue() { return value; } }
表達式
public class Expression { private Integer x; private Integer y; private Operator operator; public Expression(Integer x, Integer y, Operator operator) { this.x = x; this.y = y; this.operator = operator; } public Integer getX() { return x; } public Integer getY() { return y; } public Operator getOperator() { return operator; } }
規則引擎RuleEngine.java
import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class RuleEngine { private static List<Rule> rules = new ArrayList<>(); static { rules.add(new AddRule()); } public Result process(Expression expression) { Rule rule = rules.stream() .filter(r -> r.evaluate(expression)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule")); return rule.getResult(); } }
測試demo
@Test public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() { Expression expression = new Expression(5, 5, Operator.ADD); RuleEngine engine = new RuleEngine(); Result result = engine.process(expression); assertNotNull(result); assertEquals(10, result.getValue()); }
4.比較
重構方式 | SRP | OCP | DIP | LSP | LD | CARP |
---|---|---|---|---|---|---|
IF/ELSE | N | N | N | N | N | N |
工廠方法 | Y | Y | Y | Y | Y | Y |
枚舉方法 | N | Y | Y | Y | Y | Y |
命令模式 | Y | Y | Y | Y | Y | Y |
規則引擎 | Y | Y | Y | Y | Y | Y |
5.小結
為了更好的代碼重用性,可讀性,可靠性,可維護性,我們會嘗試將IF/ELSE或者case-switch進行改造,使用工廠方法,枚舉方法,命令模式,規則引擎方式不同方法進行嘗試,最后使用設計模式的六大原則對代碼進行評估。
看完上述內容,是不是對java消除大量的if else判斷的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。