好的,我准备根据您的解释尝试一下。如果这不是您想要的,我们可以努力寻找更合适的解决方案。另外,请原谅我对地理的有限掌握;)。
首先,我将定义我们的数据模型。我们有以下对位置建模的事实类:
package de.jannik.locationrules;
public class VisitedLocation {
private String name;
public VisitedLocation(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
然后,我们有一个模拟用户的类。我们只需要对您要调用的方法进行此操作:
package de.jannik.locationrules;
public class User {
public void handleVisitedContinent(String continentName) {
System.out.println("User has been to " + continentName + ".");
}
}
现在我们可以根据这些模型类来描述业务需求:
package de.jannik.drltest
import de.jannik.locationrules.VisitedLocation;
import de.jannik.locationrules.User;
global User user;
rule "User has been to Europe"
when
exists VisitedLocation(name in ("Berlin", "Paris", "London", "Rome"))
then
user.handleVisitedContinent("Europe");
end
rule "User has been to Australia"
when
exists VisitedLocation(name in ("Melbourne", "Sydney"))
then
user.handleVisitedContinent("Australia");
end
rule "User has been to America"
when
exists VisitedLocation(name in ("San Francisco", "New York", "Buenos Aires"))
then
user.handleVisitedContinent("America");
end
在这里,我制定了许多规则,这些规则根据工作内存中存在的 sUser.handleVisitedContent(String)
使用不同的参数调用方法。VisitedLocation
请注意,用户没有在事实中明确建模。相反,我们假设每次需要修改用户时都会创建一个新会话。根据您的业务需求和性能考虑,您可能希望将其更改为仅对所有用户使用单个会话。
这是我用来执行我定义的规则的代码:
...
@Test
public void testLocationRules() {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("locations.drl"), ResourceType.DRL);
if (kbuilder.hasErrors()) {
KnowledgeBuilderErrors errors = kbuilder.getErrors();
System.out.println(errors.toString());
throw new RuntimeException(errors.toString());
}
KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
knowledgeBase.addKnowledgePackages(kbuilder.getKnowledgePackages());
StatelessKnowledgeSession session = knowledgeBase.newStatelessKnowledgeSession();
session.setGlobal("user", new User());
List<VisitedLocation> facts = new ArrayList<VisitedLocation>();
facts.add(new VisitedLocation("Berlin"));
facts.add(new VisitedLocation("Paris"));
facts.add(new VisitedLocation("San Francisco"));
facts.add(new VisitedLocation("Saigon"));
session.execute(facts);
}
...
这将产生以下输出:
User has been to America.
User has been to Europe.
如果这不是您想要的或者您需要进一步澄清,请告诉我。此外,您可能需要查阅Drools 专家用户指南以获取有关 Drools 概念的更多解释。