Drools Rule Templates

Drools 5 sees the addition of a new feature - rule templates. Rule templates allow you to set up templates (!) that may then be merged with data. You can think of them as similar to decision tables but far more powerful. With Rule Templates the data is separated from the rule and there are no restrictions on which part of the rule is data-driven. So whilst you can do everything you could do in decision tables you can also do the following:

  • store your data in a database (or any other format)
  • conditionally generate rules based on the values in the data
  • use data for any part of your rules (e.g. condition operator, class name, property name)
  • run different templates over the same data

I find the best way to explain things is via example so over a few posts I will take you through three of the examples in the drools-examples project. The first shows how to achieve exactly the same functionality as a decision table using a rule template. The second example extends the first to include array fields and optional fields. The third gives an example of using a rule template with a different datasource - in this case Plain Old Java Objects (POJOs), and conditional templates.

template header//必须以“template header”开头
age
type
log
//空格,column名称结束
package org.drools.examples.templates;
global java.util.List list;
template "cheesefans"//开始template
rule "Cheese fans_@{row.rowNumber}"
    when
        Person(age == @{age})
        Cheese(type == "@{type}")
    then
        list.add("@{log}");
end
end template//结束template

Line 1: all rule templates start with "template header"
Lines 2-4: following the header is the list of columns in the order they appear in the data. In this case we are calling the first column "age", the second "type" and the third "log".
Lines 5: empty line signifying the end of the column definitions
Lines 6-9: standard rule header text. This is standard rule DRL and will appear at the top of the generated DRL. Put the package statement and any imports and global definitions
Line 10: The "template" keyword signals the start of a rule template. There can be more than one template in a template file. The template should have a unique name.
Lines 11-18: The rule template - see below
Line 20: "end template" signifies the end of the template.

Drools 5 中增加的新功能,解决规则中的数据来源问题,使用数据库中定义的数据替换模版中相应的占位符,批量生成规则,很实用。

现在使用的Drools 5.3.0.Final中只是发布了核心类和接口的API,但具体实现类并没有文档说明,只能自己看源代码。

例如整个decisiontable.jar,这里用到ExternalSpreadsheetCompiler类,编译xls、csv表格文件到drl语句。

 

原文出自http://planet.jboss.org/post/drools_rule_templates ,发表于2008-08-26 


 


posted @ 2012-02-21 15:44  kaqike  阅读(1188)  评论(0编辑  收藏  举报