if 或 java_Java重构—去除多余的if-else

当出现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;

}

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;

}嵌套逻辑比较多的时候优化方案,有非常多的重构方法来解决这个问题, 这里会列举很多方法,在实际应用中可能会根据场景进行一些调整;

1.工厂类定义一个操作接口

public interface Operation {

int apply(int a, int b);

}实现操作, 这里只以add为例

public class Addition implements Operation {

@Override

public int apply(int a, int b) {

return a + b;

}

}实现操作工厂

public class OperatorFactory {

static Map operationMap = new HashMap<>();

static {

operationMap.put("add", new Addition());

operationMap.put("divide", new Division());

// more operators }

public static Optional getOperation(String operator) {

return Optional.ofNullable(operationMap.get(operator));

}

}在Calculator中调用

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 代表“成功”,2 代表“失败”,但是如果直接把 1 和 2 写到代码中,别人看的时候很可能不知道这两个数字的具体含义,这个时候可以利用枚举类,将数字的意思明确地摆出来,以下是应用实例:定义操作符枚举

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

}在Calculator中调用

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.命令模式什么是命令模式

命令(Command)模式又叫作动作(Action)模式或事务(Transaction)模式,是一种对象的行为模式。将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。

命令模式的本质:封装请求

设计意图:命令模式通过将请求封装到一个命令(Command)对象中,实现了请求调用者和具体实现者之间的解耦。命令模式适用性

如果需要抽象出需要执行的动作,并参数化这些对象,可以选用命令模式。将这些需要执行的动作抽象成为命令,然后实现命令的参数化配置。

如果需要在不同的时刻指定、排列和执行请求,可以选用命令模式。将这些请求封装成为命令对象,然后实现将请求队列化。

如果需要支持取消操作,可以选用命令模式,通过管理命令对象,能很容易地实现命令的恢复和重做功能。

如果需要支持当系统崩溃时,能将系统的操作功能重新执行一遍,可以选用命令模式。将这些操作功能的请求封装成命令对象,然后实现日志命令,就可以在系统恢复以后,通过日志获取命令列表,从而重新执行一遍功能。

在需要事务的系统中,可以选用命令模式。命令模式提供了对事务进行建模的方法。命令模式有一个别名就是Transaction。命令模式的结构Command接口

public interface Command {

Integer execute();

}实现Command

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;

}

}在Calculator中调用

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)仍然没有解决动态获取操作符问题,所以通常来说可以结合简单工厂模式来调用简单工厂(Simple Factory),它把实例化的操作单独放到一个类中,这个类就成为简单工厂类,让简单工厂类来决定应该用哪个具体子类来实例化,这样做能把客户类和具体子类的实现解耦,客户类不再需要知道有哪些子类以及应当实例化哪个子类

4.规则引擎将规则引擎想象成一个以数据和规则作为输入的系统。它将这些规则应用于数据,并根据规则定义为我们提供输出。定义规则

public interface Rule {

boolean evaluate(Expression expression);

Result getResult();

}Add 规则

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;

}

}表达式

public class Expression {

private Integer x;

private Integer y;

private Operator operator;

}规则引擎

public class RuleEngine {

private static List 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());

}

5.策略模式策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。策略模式的结构

策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。用一句话来说,就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”。下面就以一个示意性的实现讲解策略模式实例的结构。

这个模式涉及到三个角色:环境(Context)角色:持有一个Strategy的引用。

抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。操作

public interface Opt {

int apply(int a, int b);

}

@Component(value = "addOpt")

public class AddOpt implements Opt {

@Autowired

xxxAddResource resource; // 这里通过Spring框架注入了资源

@Override

public int apply(int a, int b) {

return resource.process(a, b);

}

}

@Component(value = "devideOpt")

public class devideOpt implements Opt {

@Autowired

xxxDivResource resource; // 这里通过Spring框架注入了资源

@Override

public int apply(int a, int b) {

return resource.process(a, b);

}

}策略

@Component

public class OptStrategyContext{

private Map strategyMap = new ConcurrentHashMap<>();

@Autowired

public OptStrategyContext(Map strategyMap) {

this.strategyMap.clear();

this.strategyMap.putAll(strategyMap);

}

public int apply(Sting opt, int a, int b) {

return strategyMap.get(opt).apply(a, b);

}

}

参考文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值