Drools JBOSS rule Nested IF's

此生再无相见时 提交于 2019-12-04 19:09:53

The concept of "else" doesn't really translate directly to a declarative language. Instead, you have to explicitly define what "else" truly means in terms of your data and write a rule (or rules) based on that condition. As an example, consider the following conditions:

If Order Total >= 1000
  Discount = 15%
Else If Order Total >= 500
  Discount = 10%
Else If Order Total >= 250
  Discount = 5%
Else
  Discount = 0%

The natural first attempt at rules for these conditions might be:

rule "15% discount"
  when
    $o : Order( total >= 1000 )
  then
    modify($o) { setDiscount(.15); }
end

rule "10% discount"
  when
    $o : Order( total >= 500 )
  then
    modify($o) { setDiscount(.10); }
end

etc...

The problem with this approach is that both the 10% and 15% rules will match for an Order whose total is 1200. This is because the "else" part of "else if" inherently includes the condition that the order total is not greater than 1000. So we write our rules like this instead:

rule "15% discount"
  when
    $o : Order( total >= 1000, discount == null )
  then
    modify($o) { setDiscount(.15); }
end

rule "10% discount"
  when
    $o : Order( total >= 500, total < 1000, discount == null )
  then
    modify($o) { setDiscount(.10); }
end

rule "5% discount"
  when
    $o : Order( total >= 250, total < 500, discount == null )
  then
    modify($o) { setDiscount(.05); }
end

rule "no discount"
  when
    $o : Order( total < 250, discount == null )
  then
    modify($o) { setDiscount(0); }
end

(You'll notice I also added a discount == null condition. This is to prevent the rule from reactivating when the Order fact is updated.)

I've been focusing on a simple example rather than your specific use case to demonstrate the concept of writing a condition to mimic an "else". I'm still not sure I completely understand your use case, but hopefully I've answered the key conceptual part of your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!