drools rules inheritance

2019-06-26 03:32发布

I am new to drools and am familiar with using the extends keyword to inherit a rule. Question is there a way to inherit multiple rules? This would be similar to using multiple interfaces on a java class. Here's an example of how I would expect it to work but I get an error on rule 3:

rule "rule 1"
when //person name == "John"
then //print "John"
end

rule "rule 2"
when //person last name == "Smith"
then //print "Smith"
end

rule "rule 3" extends "rule 1", "rule 2"
when //person age > 20
then //print John Smith is older than 20
end

Thanks Dawn

标签: drools
2条回答
该账号已被封号
2楼-- · 2019-06-26 04:25

I know that this thread is old but it's possible to do the following:

rule "first name is John rule"
    when
        $p : Person(  name == 'John' )
    then
end

rule "last name is Smith rule" extends "first name rule"
    when
        eval( $p.getLastName() == "Smith" )
    then
end

rule "age older than 20 rule" extends "last name rule"
    when
        eval ( $p.getAge() > 20 )
    then
        System.out.println($p.getFirstName() + " " + $p.getLastName() +
                " is older than 20");
end

rule "age younger than 20 rule" extends "last name rule"
    when
        eval ( $p.getAge() < 20 )
    then
        System.out.println($p.getFirstName() + " " + $p.getLastName() +
                " is younger than 20");
end

As you can see, you can create a chained rule from super rules inheriting their declared variables.

查看更多
ら.Afraid
3楼-- · 2019-06-26 04:33

It isn't well documented yet, but single inheritance does exist in drools. It allows you to create a rule that extends another rule. The sub rule will fire if and only if both of the conditions for the super rule AND the sub rule are true. (See my notes at the bottom).

In the example below, "Flags" is a simple Java class with 2 booleans: isSuperTrue and isSubTrue. The magic phrase is extends "super" as part of the "sub" rule definition. The names of the rules (sub and super) are illustrative and can be changed to any legal rule name.

rule "super" 
    @description("Fires when isSuperTrue is true regardless of the state of isSubTrue")
    when
        $flag : Flags(isSuperTrue == true)
    then
        System.out.println("super rule should fire anytime super is true and ignore sub");
end

rule "sub" extends "super"
    @description("Fires only when both isSubTrue and isSuperTrue are true")
    when
        Flags(isSubTrue == true)        
    then
        System.out.println("sub rule should fire when both isSubTrue and isSuperTrue are true");
end

Note 1: There is an issue in 5.5.0.Final that requires the super rule to be placed before the sub rule in the rule definition file. I've confirmed that the bug is fixed for 5.6.0.CR1.

Note 2: This functionality is indirectly documented in the release notes for 5.5.0.Final in section 4.1.1.3. The core topic is "Conditional named consequences," but it leverages rule inheritance.

查看更多
登录 后发表回答