# 探讨if...else的替代方案

## 业务需求

public static int calculate(int a, int b, String operator) {
int result = Integer.MIN_VALUE;
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;
}
return result;
}


public static int calculateUsingSwitch(int a, int b, String operator) {
int result = 0;
switch (operator) {
result = a + b;
break;
case "subtract":
result = a - b;
case "divide":
result = a / b;
break;
case "multiply":
result = a * b;
}
return result;
}

## 重构方案

### 1.工厂模式

1.将操作抽象成一个Operation接口。

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

2.分别实现加减乘除四个方法。

public class Addition implements Operation {

@Override
public int apply(int a, int b) {
return a + b;
}
}

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

// other case


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("divide", new Division());
// more operators
}

public static Optional<Operation> getOperation(String operator) {
return Optional.ofNullable(operationMap.get(operator));
}
}

3.调用

public int calculateUsingFactory(int a, int b, String operator) {
Operation targetOperation = OperatorFactory
.getOperation(operator)
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
return targetOperation.apply(a, b);
}

### 2.使用枚举

1. 我们需要定义加减乘除的Enum。

public enum Operator {
}


ADD {
@Override
public int apply(int a, int b) {
return a + b;
}
},
// other operators

public abstract int apply(int a, int b);


1. 在计算器类中，可以定义一个方法来执行该操作。

public int calculate(int a, int b, Operator operator) {
return operator.apply(a, b);
}

3. 可以通过使用Operator#valueOf()方法将字符串值转换为操作符来调用该方法。

@Test
public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
assertEquals(7, result);
}

### 3.命令模式

1. 定义命令接口

public interface Command {
Integer execute();
}


public class AddCommand implements Command {
// Instance variables

public AddCommand(int a, int b) {
this.a = a;
this.b = b;
}

@Override
public Integer execute() {
return a + b;
}
}

3. 在计算器中引入一个新方法，接受并执行命令。

public int calculate(Command command) {
return command.execute();
}


@Test
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculate(new AddCommand(3, 7));
assertEquals(10, result);
}


### 4.规则引擎

1. 定义一个规则接口。

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


2. 实现一个RuleEngine。

public class RuleEngine {
private static List<Rule> rules = new ArrayList<>();

static {
}

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

public class Expression {
private Integer x;
private Integer y;
private Operator operator;
}

public class AddRule implements Rule {
@Override
public boolean evaluate(Expression expression) {
boolean evalResult = false;
this.result = expression.getX() + expression.getY();
evalResult = true;
}
return evalResult;
}
}

2. 用一个表达式来调用RuleEngine。

@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());

}

## 往期文章推荐

posted @ 2022-07-24 18:24  QualityAssurance21  阅读(109)  评论(0编辑  收藏  举报