【问题标题】:How to refactor the following drools rule criteria into a function?如何将以下drools规则标准重构为函数?
【发布时间】:2013-10-10 21:56:06
【问题描述】:
rule "size must be greater than 1 billion"
    when
        $typeMaster : TypeMaster ( $type : keyValue["type"] , 
                                   $code : keyValue["code"],
                                       ( $type in ( "CB1", "CB2" ) && $code == "123" ) ||
                                       ( $type in ( "B1", "B2" ) && $code == "234" ) &&
                                   keyValue["size"] <= 1000000000 )
    then
        messageService.save(Type.ERROR, kcontext, $typeMaster);
end

我在流口水中有上述规则,在 TypeMaster 事实/对象中说,有一个 keyValue 映射,获取类型和代码并根据几个标准检查它们的值,当它们满足时,检查大小是否

我想重构代码。但是,我希望所有类型和代码检查都在规则文件中,因为如果任何规则发生更改,可以在文件本身中更改它,而不是进入 Java 代码并更改硬编码变量。你能推荐一下吗?

【问题讨论】:

    标签: java drools


    【解决方案1】:

    如何将检查方法添加到您的 TypeMaster Fact。像这样的

    class TypeMaster {
      boolean isTypeIn( String... params ) {
        // Check if this.type is in params
      }
      boolean isCodeIn( String... params ) {
        // Check if this.code is in params
      }
      boolean isSizeSmallerOrEqualTo( long value ) {
        return this.size <= value  // You might not need this util method
      }
    }
    

    那么在你的规则中你会有这样的东西

    rule "size must be greater than 1 billion"
        when
            $typeMaster : TypeMaster ( typeIn( "CB1", "CB2" ) && codeIn( "123" ) ||
                                       typeIn( "B1", "B2" ) && codeIn( "234" ) &&
                                       sizeSmallerOrEqualTo( 1000000000  )
        then
            messageService.save(Type.ERROR, kcontext, $typeMaster);
    end
    

    我现在无法验证在从 Drools 调用方法时 var args 参数是否有效,但如果它失败了,您可以使用数组、多个参数等

    另一种选择是在 TypeMaster 中覆盖 getType()getCode(),这样它将直接返回值而不是通过 map 获取它们。像这样

    class TypeMaster {
      Map values // this represents your key-value map
      getType() {
        return values.get( "type" )
      }
      getCode() {
        return values.get( "code" )
      }
      // getSize() similarly
    }
    

    在此之后,您的规则不会有太大变化

    rule "size must be greater than 1 billion"
        when
            $typeMaster : TypeMaster ( ( $type in ( "CB1", "CB2" ) && $code == "123" ) ||
                                       ( $type in ( "B1", "B2" ) && $code == "234" ) &&
                                         size <= 1000000000 )
        then
            messageService.save(Type.ERROR, kcontext, $typeMaster);
    end
    

    希望你能明白。

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多