当前位置:   article > 正文

Java 中替代 if else

Java 中替代 if else

copy 的其他博主的,后续弄懂了,会进行大幅度修改

参考博客: Java中的大量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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

二、简单替代 switch

public int calculateUsingSwitch(int a, int b, String operator) {
    switch (operator) {
    case "add":
        result = a + b;
        break;
    // other cases    
    }
    return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

三、复杂替代

1. 工厂类

  • 抽象接口
    public interface Operation {
    	int apply(int a, int b);
    }
    
    • 1
    • 2
    • 3
  • 实现方法
    public class Addition implements Operation {
    	@Override
    	public int apply(int a, int b) {
        	return a + b;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 工厂提供操作
    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));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 调用
    public int calculateUsingFactory(int a, int b, String operator) {
    	Operation targetOperation = OperatorFactory
      		.getOperation(operator)
      		.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
    	return targetOperation.apply(a, b);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

2. 枚举

  • 枚举中定义操作
    public enum Operator {
    	ADD, MULTIPLY, SUBTRACT, DIVIDE
    }
    
    • 1
    • 2
    • 3
  • 编写抽象方法
    ADD {
    	@Override
    	public int apply(int a, int b) {
        	return a + b;
    	}
    },
    // other operators
    
    public abstract int apply(int a, int b);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 调用时传入枚举值
    public int calculate(int a, int b, Operator operator) {
    	return operator.apply(a, b);
    }
    
    • 1
    • 2
    • 3
  • 测试
    @Test
    public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
    	Calculator calculator = new Calculator();
    	int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
    	assertEquals(7, result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

3. 命令模式

  • 定义命令接口
    public interface Command {
    	Integer execute();
    }
    
    • 1
    • 2
    • 3
  • 实现加法
    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;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 定义Calculator类,加入执行命令的方法
    public int calculate(Command command) {
    	return command.execute();
    }
    
    • 1
    • 2
    • 3
  • 测试
    @Test
    public void whenCalculateUsingCommand_thenReturnCorrectResult() {
    	Calculator calculator = new Calculator();
    	int result = calculator.calculate(new AddCommand(3, 7));
    	assertEquals(10, result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

4. 规则引擎

  • 定义规则接口
    public interface Rule {
    	boolean evaluate(Expression expression);
    	Result getResult();
    }
    
    • 1
    • 2
    • 3
    • 4
  • 实现规则引擎
    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();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 定义表达式
    public class Expression {
    	private Integer x;
    	private Integer y;
    	private Operator operator;        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 定义加法规则
    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;
    	}    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 测试
    @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());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/377768
推荐阅读
相关标签
  

闽ICP备14008679号