日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java如何消除太多的if else判断?

發(fā)布時間:2025/4/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java如何消除太多的if else判断? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1.簡介

if判斷語句是很多編程語言的重要組成部分。但是,若我們最終編寫了大量嵌套的if語句,這將使得我們的代碼更加復(fù)雜和難以維護(hù)。

讓我們看看能否使用別的方式來做呢。

設(shè)計(jì)模式是為了更好的代碼重用性,可讀性,可靠性,可維護(hù)性,它有六大原則

      1)單一職責(zé)原則(Single Responsibility Principle,簡稱SRP):該原則是針對類來說的,即一個類應(yīng)該只負(fù)責(zé)一項(xiàng)職責(zé).
      2)開放--封閉原則(The Open-Closed Principle簡稱OCP):是說軟件實(shí)體(類、模塊、函數(shù)等等)應(yīng)該可以擴(kuò)展,但是不可以修改。
      3)依賴倒轉(zhuǎn)原則(Dependence Inversion Principle?:針對接口編程,不要對實(shí)現(xiàn)編程
      4)里氏代換原則(Liskov Substitution Principle,簡稱LSP):里氏代換原則,子類型必須能夠替換掉他們的父類型
      5)迪米特法則(Law of Demeter):如果兩個類不必彼此直接通信,那么這兩個類就不應(yīng)當(dāng)發(fā)生直接的相互作用
      6)合成/聚合復(fù)用原則(Composition/Aggregation Principle],簡稱CARP):盡量使用合成/聚合,盡量不使用類繼承。合成聚合是“has ?a”的關(guān)系,而繼承是“is ?a”的關(guān)系。

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;}

case-switch

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.重構(gòu)

3.1 工廠方式重構(gòu)

抽象層Operation.java

public interface Operation {int apply(int a, int b); }

加法實(shí)現(xiàn)Addition.java:

public class Addition implements Operation {@Overridepublic int apply(int a, int b) {return a + b;} }

減法實(shí)現(xiàn)Subtraction.java

public class Subtraction implements Operation {@Override public int apply(int a, int b) {return a - b;} }

乘法實(shí)現(xiàn)Multiplication.java

public class Multiplication implements Operation {@Override public int apply(int a, int b) {return a*b;} }

除法實(shí)現(xiàn)Division.java

public class Division implements Operation {@Override public int apply(int a, int b) {return a / b;} }

求余實(shí)現(xiàn)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 枚舉方式重構(gòu)

枚舉實(shí)現(xiàn)Operator.java

public enum Operator {ADD {@Overridepublic int apply(int a, int b) {return a + b;}},MULTIPLY {@Overridepublic int apply(int a, int b) {return a * b;}},SUBTRACT {@Overridepublic int apply(int a, int b) {return a - b;}},DIVIDE {@Overridepublic int apply(int a, int b) {return a / b;}},MODULO {@Overridepublic 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(); }

實(shí)現(xiàn)類

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;}@Overridepublic 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); }

?

4.規(guī)則引擎重構(gòu)

抽象規(guī)則

public interface Rule {boolean evaluate(Expression expression);Result getResult(); }

實(shí)現(xiàn)規(guī)則AddRule.java 其它略

public class AddRule implements Rule {private int result;@Overridepublic boolean evaluate(Expression expression) {boolean evalResult = false;if (expression.getOperator() == Operator.ADD) {this.result = expression.getX() + expression.getY();evalResult = true;}return evalResult;}@Overridepublic Result getResult() {return new Result(result);} }

?

其中:返回結(jié)果

public class Result {int value;public Result(int value) {this.value = value;}public int getValue() {return value;} }

表達(dá)式

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;} }

規(guī)則引擎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.比較

重構(gòu)方式SRPOCPDIPLSPLDCARP
IF/ELSENNNNNN
工廠方法YYYYYY
枚舉方法NYYYYY
命令模式YYYYYY
規(guī)則引擎YYYYYY

?

5.小結(jié)

? 為了更好的代碼重用性,可讀性,可靠性,可維護(hù)性,我們會嘗試將IF/ELSE或者case-switch進(jìn)行改造,使用工廠方法,枚舉方法,命令模式,規(guī)則引擎方式不同方法進(jìn)行嘗試,最后使用設(shè)計(jì)模式的六大原則對代碼進(jìn)行評估。

參考資料

【1】https://www.cnblogs.com/davidwang456/p/3641369.html

【2】https://www.baeldung.com/java-replace-if-statements

轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/10831546.html

總結(jié)

以上是生活随笔為你收集整理的java如何消除太多的if else判断?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。