-
Notifications
You must be signed in to change notification settings - Fork 31
JSON 配置
Anthony Li edited this page May 9, 2016
·
2 revisions
g-rule 支持通过 JSON 配置文件自动装配规则链。下面,在主页的第一个应用的基础上,演示该功能如何使用:
旧的代码:
Condition age = new AgeCondition();
Action adult = new AdultAction();
Action child = new ChildAction();
age.registerTrueUnit(adult);
age.registerFalseUnit(child);
Context context = new SimpleContext();
context.put("age", new Integer(16));
RuleEngine.getInstance().setEntry(age).run(context);
使用了 JSON 配置自动装配的代码:
{
"type": "condition", // ①
"class": "com.example.AgeCondition", // ②
"true_unit": { // ③
"type": "action",
"class": "com.example.AdultAction"
},
"false_unit": { // ④
"type": "action",
"class": "com.example.ChildAction"
}
}
① 规则的类型,可选值为 action 或 condition
② 规则实现类的类名
③ 当条件为真时,执行的单元
④ 当条件为假时,执行的单元
Context context = new SimpleContext();
context.put("age", new Integer(16));
RuleEngine.getInstance().config(json).run(context);
type 规则的类型,当前仅支持 action 或 condition
class 实现类的类名
true_unit 仅在 type 为 condition 时有效,条件为真时,下一个单元的配置
false_unit 仅在 type 为 condition 时有效,条件为假时,下一个单元的配置
unit 仅在 type 为 action 时有效,下一个单元的配置
fields 字段值,为规则实例的字段赋值,示例:
{
"type": "condition",
"class": "com.example.TestAction",
"fields": {
"name": "Anthony",
"age": 22
}
}
public class TestAction extends AbstractAction {
private String name;
private int age;
@Override
public void run(Context context) throws UnitRunException {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
// output:
// Name: Anthony
// Age: 22