最为常见的是代码中使用很多的if/else,或者switch/case;如何重构呢?方法特别多,本文是设计模式第八讲,带你学习其中的技巧。
通常业务代码会包含这样的逻辑:每种条件下会有不同的处理逻辑。比如两个数a和b之间可以通过不同的操作符(+,-,*,/)进行计算,初学者通常会这么写:
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;
}
return result;
}
或者用switch/case:
public int calculateUsingSwitch(int a, int b, String operator) {
switch (operator) {
case "add":
result = a + b;
break;
// other cases
}
return result;
}
这种最基础的代码如何重构呢?
有非常多的重构方法来解决这个问题, 这里会列举很多方法,在实际应用中可能会根据场景进行一些调整;另外不要纠结这些例子中显而易见的缺陷(比如没用常量,没考虑多线程等等),而是把重心放在学习其中的思路上。
工厂设计模式可以参考这篇文章:JAVA设计模式第二讲:创建型设计模式
第8.2节
定义一个操作接口
public interface Operation {
int apply(int a, int b);
}
public class Addition implements Operation {
@Override
public int apply(int a, int b) {
return a + b;
}
}
public class OperatorFactory {
static Map<String, Operation> operationMap = new HashMap<>();
static {
operationMap.put("add", new Addition());
operationMap.put("divide", new Division());
// more operators
}
public static Optional<Operation> getOperation(String operator) {
return Optional.ofNullable(operationMap.get(operator));
}
}
public int calculateUsingFactory(int a, int b, String operator) {
Operation targetOperation = OperatorFactory
.getOperation(operator)
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
return targetOperation.apply(a, b);
}
对于上面为什么方法名是apply
,Optional
怎么用? 请参考这篇:
枚举适合类型固定,可枚举的情况,比如如下操作符;同时枚举中是可以提供方法实现的,这就是我们可以通过枚举进行重构的原因。
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);
}
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);
}
看是否很简单?
命令模式也是非常常用的重构方式,把每个操作符当作一个Command。
首先让我们回顾下什么是命令模式
Command接口
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;
}
}
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);
}
注意,这里new AddCommand(3, 7)
仍然没有解决动态获取操作符问题,所以通常来说可以结合简单工厂模式来调用:
规则引擎适合规则很多且可能动态变化的情况,在先要搞清楚一点Java OOP,即类的抽象:
public interface Rule {
boolean evaluate(Expression expression);
Result getResult();
}
public class AddRule implements Rule {
@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() {
...
}
}
public class Expression {
private Integer x;
private Integer y;
private Operator operator;
}
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();
}
}
@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());
}
策略模式比命令模式更为常用,而且在实际业务逻辑开发中需要注入一定的(比如通过Spring的
@Autowired
来注入bean),这时通过策略模式可以巧妙的重构
什么是策略模式?
Spring中需要注入资源重构?
如果是在实现业务逻辑需要注入框架中资源呢?比如通过Spring的
@Autowired
来注入bean。可以这样实现:
public interface Opt {
int apply(int a, int b);
}
@Component(value = "addOpt")
public class AddOpt implements Opt {
// 这里通过Spring框架注入了资源
@Autowired
xxxAddResource resource;
@Override
public int apply(int a, int b) {
return resource.process(a, b);
}
}
@Component(value = "devideOpt")
public class devideOpt implements Opt {
// 这里通过Spring框架注入了资源
@Autowired
xxxDivResource resource;
@Override
public int apply(int a, int b) {
return resource.process(a, b);
}
}
@Component
public class OptStrategyContext{
private Map<String, Opt> strategyMap = new ConcurrentHashMap<>();
@Autowired
public OptStrategyContext(Map<String, Opt> strategyMap) {
this.strategyMap.clear();
this.strategyMap.putAll(strategyMap);
}
public int apply(Sting opt, int a, int b) {
return strategyMap.get(opt).apply(a, b);
}
}
上述代码在实现中非常常见。
最怕的是刚学会成语,就什么地方都想用成语。
最怕的是刚学会成语,就什么地方都想用成语
; 很多时候不是考虑是否是最佳实现,而是折中(通常是业务和代价的折中,开发和维护的折中…),在适当的时候做适当的重构。