drools Rule (四) 有条件命名的后果Conditional named consequences

有时,对每个规则具有单一结果的约束可能会有所限制,并导致冗长且难以维持的重复,如下例所示:

rule "Give 10% discount to customers older than 60"
when
    $customer : Customer( age > 60 )
then
    modify($customer) { setDiscount( 0.1 ) };
end

rule "Give free parking to customers older than 60"
when
    $customer : Customer( age > 60 )
    $car : Car ( owner == $customer )
then
    modify($car) { setFreeParking( true ) };
end

已经可以通过使第二个规则扩展第一个规则来部分克服这个问题,如:

rule "Give 10% discount to customers older than 60"
when
    $customer : Customer( age > 60 )
then
    modify($customer) { setDiscount( 0.1 ) };
end

rule "Give free parking to customers older than 60"
    extends "Give 10% discount to customers older than 60"
when
    $car : Car ( owner == $customer )
then
    modify($car) { setFreeParking( true ) };
end

无论如何,这个特性使得在单个规则中定义除了默认值之外的更多标记后果成为可能,因此,例如,前两个规则可以仅按照如下方式压缩:

rule "Give 10% discount and free parking to customers older than 60"
when
    $customer : Customer( age > 60 )
    do[giveDiscount]
    $car : Car ( owner == $customer )
then
    modify($car) { setFreeParking( true ) };
then[giveDiscount]
    modify($customer) { setDiscount( 0.1 ) };
end

最后一条规则有2个后果,通常是默认值,加上另一个名为“giveDiscount”,使用关键字do激活,只要在KIEbase找到60岁以上的客户,无论他是不是有car。命名结果的激活也可以通过附加条件来保护,如下一个示例所示:

rule "Give free parking to customers older than 60 and 10% discount to golden ones among them"
when
    $customer : Customer( age > 60 )
    if ( type == "Golden" ) do[giveDiscount]
    $car : Car ( owner == $customer )
then
    modify($car) { setFreeParking( true ) };
then[giveDiscount]
    modify($customer) { setDiscount( 0.1 ) };
end

始终直接评估if语句。最后,这个更复杂的示例显示了如何使用嵌套的if / else语句切换不同的条件:

rule "Give free parking and 10% discount to over 60 Golden customer and 5% to Silver ones"
when
    $customer : Customer( age > 60 )
    if ( type == "Golden" ) do[giveDiscount10]
    else if ( type == "Silver" ) break[giveDiscount5]
    $car : Car ( owner == $customer )
then
    modify($car) { setFreeParking( true ) };
then[giveDiscount10]
    modify($customer) { setDiscount( 0.1 ) };
then[giveDiscount5]
    modify($customer) { setDiscount( 0.05 ) };
end

这里的目的是给予超过60岁的Golden顾客10%的折扣和免费停车,但只有5%的折扣(没有免费停车)给Silver。通过使用关键字break而不是do来激活名为“giveDiscount5”的结果来实现此结果。实际上,只需在agenda中安排一个结果,允许LHS的剩余部分继续按照正常情况进行评估,而break也会阻止任何进一步的模式匹配评估。当然,请注意,激活任何没有被中断条件保护的命名结果都没有意义(并产生编译时错误),否则跟随它的LHS部分将永远不可达。

猜你喜欢

转载自blog.csdn.net/top_explore/article/details/93877366