java “if then else”规则引擎

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7993659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:36:07  来源:igfitidea点击:

"if then else "with rule engines

javarulesdroolsrule-engine

提问by Ricky Bobby

I'm new to drools and given a condition (Condition) and a boolean variable "a" , I would like to create the following rule with drools :

我是 drools 的新手,并给出了一个条件 (Condition) 和一个布尔变量 "a" ,我想用 drools 创建以下规则:

if (Condition)
   { 
    a = true;
   }
else
   {
    a = false;
   }

What is the best way to do it ?

最好的方法是什么?

For the time being I have 2 options :

目前我有两个选择:

1.Create 2 rules with Condition and not contidition (If ... then ... , If not ... then ...)

1.用条件而不是条件创建2条规则(如果......那么......,如果不是......那么......)

rule "test"
where
  $o: Object( Condition)
then 
  $o.a = true;
end


rule "test2"
where
  $o: Object( not Condition)
then 
  $o.a = false
end

2.Set the variable a to false by default and then fire the rule

2.默认将变量a设置为false,然后触发规则

rule "test"
no loop
salience 100
where 
  $o: Object()
then 
  $o.a = false;
end


rule "test"
where
  $o: Object( not Condition)
then 
  $o.a = true;
end

回答by Perception

By nature the Rete engine looks for positive matches, so yes you will need multiple rules, one for each condition check in your if-then-else block. Your first example is cleaner and more intuitive, I would go with that.

本质上,Rete 引擎会寻找正匹配,所以是的,您将需要多个规则,一个用于 if-then-else 块中的每个条件检查。你的第一个例子更清晰、更直观,我会这样做。

As an alternative, if you are processing a simple logic negation (if-else) where your variables value matches the conditional, then you can use just one rule:

作为替代方案,如果您正在处理一个简单的逻辑否定 (if-else),其中您的变量值与条件匹配,那么您可以只使用一个规则:

rule "test"
where 
  $o: Object()
then 
  $o.a = (! Condition);
end

回答by salaboy

Remember that a Rule engine is not a IF/ELSE container only. You are changing from the imperative approach of if(condition){} else {} to a declarative approach where you are letting the engine to decide and evaluate the rules based on the context (facts) that you have in your working memory.

请记住,规则引擎不仅仅是一个 IF/ELSE 容器。您正在从 if(condition){} else {} 的命令式方法转变为声明式方法,在这种方法中,您让引擎根据您工作记忆中的上下文(事实)来决定和评估规则。

Having two rules is fine, but what exactly are you trying to achieve? depending the Object structure and the business logic that you want to implement there are several ways to solve different problems. Can you give us more details about what do you want to achieve? Cheers

有两个规则很好,但你到底想达到什么目的?根据对象结构和您要实现的业务逻辑,有多种方法可以解决不同的问题。你能告诉我们更多关于你想要实现什么的细节吗?干杯