美文网首页
根据传入参数不同调用不同的方法:规则引擎重构

根据传入参数不同调用不同的方法:规则引擎重构

作者: 莫夏_b560 | 来源:发表于2019-07-16 22:32 被阅读0次

    抽象规则

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

    相关文章

      网友评论

          本文标题:根据传入参数不同调用不同的方法:规则引擎重构

          本文链接:https://www.haomeiwen.com/subject/zsixlctx.html