基于Java的带回退的简单规则引擎



我需要实现一个支持分层回退的简单规则引擎。我已经查看了DROLS库,但我不确定它是否支持我的用例。

用例非常简单,这让我思考是否需要一个规则引擎?然而,这里是用例-

我有一个模式与一堆字段

Public Class Entity {
public int val0;
public int val1;
public int val2;
public int val3;
.....
}

现在,我想根据创建针对这些字段的规则

RULE1 --- IF val0 == 1 && val1 == 1 && val2 == 1 && val3 == 1 --- (1,1,1,1) THEN DO this
RULE2 --- IF val0 == 1 && val1 == 1 && val2 == 1 && val3 == 2, --- (1,1,1,2) THEN DO this
RULE3 --- IF val0 == 1 && val1 == 1 && val2 == 1 && val3 == *, --- (1,1,1,*) THEN DO this
RULE4 --- IF val0 == 1 && val1 == 1 && val2 == * && val3 == *, --- (1,1,*,*) THEN DO this 

问题在于RULE3RULE4,其中val2和val3可以匹配任何值。

例如

val0=1, val1=1, val2=1, val3=1 -- should execute RULE1 - specific match
val0=1, val1=1, val2=1, val3=3 -- should execute RULE3 - generic match as there's no specific match for val3
val0=1, val1=1, val2=10, val3=5 -- should execute RULE4 - generic match as there's no specific match for val2 and val3

因此,根据查询的不同,我要么会找到匹配的规则,要么不得不回退到更通用的规则。是否有任何现有的规则引擎库提供此功能,或者我是否需要一个规则引擎库来实现此功能?

起初,我认为您可能需要考虑使用逐位逻辑,但由于某些字段采用非二进制值,这可能并不适用。

然而,解决方案不必那么复杂。只需创建一个类作为Entity值的匹配器,并使用if-else语句链来查找匹配项。

class EntityMatcher {
private Integer val0, val1, val2, val3;
/** Constructor used to match all the parameters */
EntityMatcher(int val0, int val1, int val2, int val3) {
// set fields 0-3
}
/** Constructor used when you don't care about val2 & val3 */
EntityMatcher(int val0, int val1) {
// set fields 0 & 1, leaving val2 and val3 as null
}
boolean matches(Entity toMatchAgainst) {
return (this.val0 == null || this.val0 == toMatchAgainst.val0)
&& (this.val1 == null || this.val1 == toMatchAgainst.val1)
...
&& (this.valN == null || this.valN == toMatchAgainst.valN);
}
}

然后你的规则引擎可能看起来像这样:

if (new EntityMatcher(1, 1, 1, 1).matches(entity))
// Rule 1
else if (new EntityMatcher(1, 1, 1, 2).matches(entity))
// Rule 2
...
else if (new EntityMatcher(1, 1).matches(entity))
// Rule 4
...
else
// no match

这与Scala中的case类本质上是相同的想法。

最新更新