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

1.简介

if判断语句是很多编程语言的重要组成部分。但是,若我们最终编写了大量嵌套的if语句,这将使得我们的代码更加复杂和难以维护。

让我们看看能否使用别的方式来做呢。

设计模式是为了更好的代码重用性,可读性,可靠性,可维护性,它有六大原则

1)单一职责原则(Single Responsibility Principle,简称SRP):该原则是针对类来说的,即一个类应该只负责一项职责.
2)开放–封闭原则(The Open-Closed Principle简称OCP):是说软件实体(类、模块、函数等等)应该可以扩展,但是不可以修改。
3)依赖倒转原则(Dependence Inversion Principle :针对接口编程,不要对实现编程
4)里氏代换原则(Liskov Substitution Principle,简称LSP):里氏代换原则,子类型必须能够替换掉他们的父类型
5)迪米特法则(Law of Demeter):如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的相互作用
6)合成/聚合复用原则(Composition/Aggregation Principle],简称CARP):尽量使用合成/聚合,尽量不使用类继承。合成聚合是“has ?a”的关系,而继承是“is ?a”的关系。

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;
        } //其他减 除 等略
        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;
        //其他减 除 等略
        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;
    }
}

乘法实现Multiplication.java

public class Multiplication 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;
}
},

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

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进行改造,使用工厂方法,枚举方法,命令模式,规则引擎方式不同方法进行尝试,最后使用设计模式的六大原则对代码进行评估

385 thoughts on “Java 如何消除太多的 if else 判断?”

  1. Pingback: Reba Fleurantin
  2. Pingback: MILFCity
  3. Pingback: premium-domains
  4. Pingback: Click Here
  5. Pingback: Click Here
  6. Pingback: Click Here
  7. Pingback: Click Here
  8. Pingback: Click Here
  9. Pingback: Click Here
  10. Pingback: Click Here
  11. Pingback: Click Here
  12. Pingback: Click Here
  13. Pingback: Click Here
  14. Pingback: Click Here
  15. Pingback: Click Here
  16. Pingback: Click Here
  17. Pingback: Click Here
  18. Pingback: Click Here
  19. Pingback: Click Here
  20. Pingback: Click Here
  21. Pingback: Click Here
  22. Pingback: Click Here
  23. Pingback: Click Here
  24. Pingback: robotics case study
  25. Pingback: Space ROS
  26. Pingback: Click Here
  27. Pingback: Reputation Defenders
  28. Pingback: Reputation Defenders
  29. Pingback: Click Here
  30. Pingback: Click Here
  31. Pingback: Click Here
  32. Pingback: Click Here
  33. Pingback: Reputation Defenders
  34. Pingback: Click Here
  35. Pingback: Click Here
  36. Pingback: Click Here
  37. Pingback: Click Here
  38. Pingback: Click Here
  39. Pingback: Click Here
  40. Pingback: Click Here
  41. Pingback: Click Here
  42. Pingback: Click Here
  43. Pingback: Click Here
  44. Pingback: Click Here
  45. Pingback: Click Here
  46. Pingback: Click Here
  47. Pingback: Click Here
  48. Pingback: grand rapids dentist
  49. Pingback: Click Here
  50. Pingback: Click Here
  51. Pingback: Click Here
  52. Pingback: Click Here
  53. Pingback: Click Here
  54. Pingback: Click Here
  55. Pingback: Click Here
  56. Pingback: Click Here
  57. Pingback: Click Here
  58. Pingback: Click Here
  59. Pingback: Click Here
  60. Pingback: Click Here
  61. Pingback: Click Here
  62. Pingback: Click Here
  63. Pingback: Click Here
  64. Pingback: refer and earn site
  65. Pingback: Click Here
  66. Pingback: Click Here
  67. Pingback: Click Here
  68. Pingback: Click Here
  69. Pingback: Click Here
  70. Pingback: Click Here
  71. Pingback: Click Here
  72. Pingback: Click Here
  73. Pingback: Click Here
  74. Pingback: Click Here
  75. Pingback: Click Here
  76. Pingback: domain-broker
  77. Pingback: top startup books
  78. Pingback: realtor ad
  79. Pingback: Google reviews
  80. Pingback: reputation defenders
  81. Pingback: 2023 Books
  82. Pingback: memorial
  83. Pingback: cemetery
  84. Pingback: death redcords
  85. Pingback: find a grave
  86. Pingback: IRA Empire
  87. Pingback: buy fluoxetine online
  88. Pingback: metformin online
  89. Pingback: tizanidine 2023
  90. Pingback: generic promethazine
  91. Pingback: buy prednisone 2023
  92. Pingback: cialis liquid
  93. Pingback: Internationalization
  94. Pingback: Faculty Building
  95. Pingback: Cloud Computing
  96. Pingback: charity
  97. Pingback: fue
  98. Pingback: MBA in FUE
  99. Pingback: ranking
  100. Pingback: lipitor 2023
  101. Pingback: mail order zyrtec
  102. Pingback: protonix
  103. Pingback: get lamictal cheap
  104. Pingback: buy celebrex 200 mg
  105. Pingback: MIS research
  106. Pingback: Bachelor's Degree
  107. Pingback: Pharmacognos
  108. Pingback: Immunizations
  109. Pingback: fue
  110. Pingback: contact fue
  111. Pingback: Pharmacy's Diploma
  112. Pingback: Maillot de football
  113. Pingback: Maillot de football
  114. Pingback: Maillot de football
  115. Pingback: Maillot de football
  116. Pingback: Maillot de football
  117. Pingback: Maillot de football
  118. Pingback: Maillot de football
  119. Pingback: Maillot de football
  120. Pingback: Maillot de football
  121. Pingback: Maillot de football
  122. Pingback: grandpashabet
  123. Pingback: cialis 20mg wirkung
  124. Pingback: SEOSolutionVIP Fiverr
  125. Pingback: SEOSolutionVIP Fiverr
  126. Pingback: SEOSolutionVIP Fiverr
  127. Pingback: binario led
  128. Pingback: Fiverr Earn
  129. Pingback: Fiverr Earn
  130. Pingback: Fiverr Earn
  131. Pingback: Fiverr Earn
  132. Pingback: Fiverr Earn
  133. Pingback: Fiverr Earn
  134. Pingback: fiverrearn.com
  135. Pingback: fiverrearn.com
  136. Pingback: fiverrearn.com
  137. Pingback: fiverrearn.com
  138. Pingback: fiverrearn.com
  139. Pingback: fiverrearn.com
  140. Pingback: Advance-Esthetic LLC
  141. Pingback: fiverrearn.com
  142. Pingback: fiverrearn.com
  143. Pingback: fiverrearn.com
  144. Pingback: quietum plus
  145. Pingback: hair loss treatment
  146. Pingback: fiverrearn.com
  147. Pingback: fiverrearn.com
  148. Pingback: weather
  149. Pingback: fiverrearn.com
  150. Pingback: fiverrearn.com
  151. Pingback: frenchie licking paws
  152. Pingback: morkie poo
  153. Pingback: jute rugs
  154. Pingback: ooohd3.ru
  155. Pingback: sitemap
  156. Pingback: cheap colchicine
  157. Pingback: 80mg cialis
  158. Pingback: buy lasix water pill
  159. Pingback: synthroid generic
  160. Pingback: prednisolone online
  161. Pingback: mail order depakote
  162. Pingback: diltiazem
  163. Pingback: norvasc cheap
  164. Pingback: Piano Removals
  165. Pingback: Piano Freight London
  166. Pingback: allegra sale walmart
  167. Pingback: tom kings kennel
  168. Pingback: cleantalkorg3.ru
  169. Pingback: vietnam tourist visa
  170. Pingback: fbofficial.ru
  171. Pingback: sorority jewelry
  172. Pingback: film
  173. Pingback: i.8ua.ru
  174. Pingback: teacup french bulldog
  175. Pingback: micro frenchie price
  176. Pingback: best budget phones
  177. Pingback: future university
  178. Pingback: future university
  179. Pingback: future university
  180. Pingback: future university
  181. Pingback: batmanapollo.ru
  182. Pingback: LORD FILM
  183. Pingback: kin
  184. Pingback: kinnit
  185. Pingback: jz
  186. Pingback: nlp
  187. Pingback: time
  188. Pingback: site
  189. Pingback: rasshifrovka karti
  190. Pingback: konsultaciya
  191. Pingback: bulldogs puppy
  192. Pingback: more
  193. Pingback: Fiverr
  194. Pingback: Fiverr.Com
  195. Pingback: merle french bulldog
  196. Pingback: grey frenchie
  197. Pingback: fue
  198. Pingback: 9999
  199. Pingback: french bulldog
  200. Pingback: lean six sigma
  201. Pingback: 7
  202. Pingback: Grand piano storage
  203. Pingback: Piano storage
  204. Pingback: FUE
  205. Pingback: FUE
  206. Pingback: FUE
  207. Pingback: FUE
  208. Pingback: Furniture handling
  209. Pingback: Organized moving
  210. Pingback: House moving
  211. Pingback: MBA programs in Egypt
  212. Pingback: 777
  213. Pingback: wlw.su
  214. Pingback: vxi.su
  215. Pingback: FiverrEarn
  216. Pingback: nlpvip.ru
  217. Pingback: FiverrEarn
  218. Pingback: FiverrEarn
  219. Pingback: FiverrEarn
  220. Pingback: FiverrEarn
  221. Pingback: russianmanagement.com
  222. Pingback: Slovo pacana 6 seriya
  223. Pingback: Fiverr
  224. Pingback: tadalafil tabs 10mg
  225. Pingback: FiverrEarn
  226. Pingback: slovo-pacana-6-seriya
  227. Pingback: FiverrEarn
  228. Pingback: manipulyation
  229. Pingback: FiverrEarn
  230. Pingback: Coach
  231. Pingback: Media
  232. Pingback: FiverrEarn
  233. Pingback: pupuk cair
  234. Pingback: partners
  235. Pingback: ikaria juice reviews
  236. Pingback: exipure
  237. Pingback: Political Theory
  238. Pingback: red boost reviews
  239. Pingback: Sport analysis
  240. Pingback: FiverrEarn
  241. Pingback: FiverrEarn
  242. Pingback: FiverrEarn
  243. Pingback: live sex cams
  244. Pingback: live sex cams
  245. Pingback: live sex cams
  246. Pingback: FiverrEarn
  247. Pingback: FiverrEarn
  248. Pingback: FiverrEarn
  249. Pingback: FiverrEarn
  250. Pingback: FiverrEarn
  251. Pingback: FiverrEarn
  252. Pingback: french bulldog
  253. Pingback: 354
  254. Pingback: FiverrEarn
  255. Pingback: FiverrEarn
  256. Pingback: FiverrEarn
  257. Pingback: FiverrEarn
  258. Pingback: FiverrEarn
  259. Pingback: FiverrEarn
  260. Pingback: FiverrEarn
  261. Pingback: FiverrEarn
  262. Pingback: FiverrEarn
  263. Pingback: A2 Milk
  264. Pingback: Link
  265. Pingback: diamond
  266. Pingback: Slot Online
  267. Pingback: Scientific Research
  268. Pingback: Kuliah Termurah
  269. Pingback: psy
  270. Pingback: FiverrEarn
  271. Pingback: FiverrEarn
  272. Pingback: FiverrEarn
  273. Pingback: FiverrEarn
  274. Pingback: FiverrEarn
  275. Pingback: kiino4k.ru
  276. Pingback: depresiya
  277. Pingback: new 2024
  278. Pingback: film2024
  279. Pingback: 123 Movies
  280. Pingback: 000
  281. Pingback: samorazvitiepsi
  282. Pingback: Generator Sales Leeds
  283. Pingback: gluconite legit
  284. Pingback: cheap sex cams
  285. Pingback: fullersears.com
  286. Pingback: live sex cams

发表评论