js规则链实现
实现 JavaScript 规则链的方法
基于责任链模式的设计
责任链模式允许将多个处理对象串联成链,请求在链上传递直至被处理。以下是实现步骤:

class Rule {
constructor(condition, action) {
this.condition = condition;
this.action = action;
this.nextRule = null;
}
setNextRule(rule) {
this.nextRule = rule;
return rule;
}
execute(context) {
if (this.condition(context)) {
this.action(context);
}
if (this.nextRule) {
this.nextRule.execute(context);
}
}
}
// 使用示例
const rule1 = new Rule(
(ctx) => ctx.value > 10,
(ctx) => { ctx.result = '大于10' }
);
const rule2 = new Rule(
(ctx) => ctx.value <= 10,
(ctx) => { ctx.result = '小于等于10' }
);
rule1.setNextRule(rule2);
rule1.execute({ value: 5 }); // 输出: { value: 5, result: "小于等于10" }
使用数组实现的轻量级规则链
对于简单场景,可以用数组存储规则并按顺序执行:

const ruleChain = [
{
condition: (ctx) => ctx.user.role === 'admin',
action: (ctx) => { ctx.access = 'full' }
},
{
condition: (ctx) => ctx.user.role === 'user',
action: (ctx) => { ctx.access = 'partial' }
}
];
function executeRules(context) {
for (const rule of ruleChain) {
if (rule.condition(context)) {
rule.action(context);
break; // 匹配后终止
}
}
}
支持异步处理的规则链
使用Promise实现异步规则链:
class AsyncRuleChain {
constructor() {
this.rules = [];
}
addRule(condition, action) {
this.rules.push({ condition, action });
}
async execute(context) {
for (const { condition, action } of this.rules) {
if (await condition(context)) {
await action(context);
break;
}
}
}
}
规则引擎库集成
现有库如json-rules-engine提供更完整的解决方案:
const { Engine } = require('json-rules-engine');
const engine = new Engine();
engine.addRule({
conditions: {
all: [{
fact: 'temperature',
operator: 'greaterThan',
value: 60
}]
},
event: {
type: 'alert',
params: {
message: '温度过高!'
}
}
});
engine.run({ temperature: 70 }).then(events => {
events.map(event => console.log(event.params.message));
});
关键实现要点
- 条件与执行分离:每个规则应包含独立的条件判断和执行逻辑
- 链式管理:明确规则间的传递关系,支持动态添加/移除规则
- 上下文传递:通过共享上下文对象实现规则间数据传递
- 终止控制:根据需求决定是否在规则匹配后终止链式执行
性能优化建议
- 对高频规则进行优先级排序
- 使用备忘录模式缓存条件计算结果
- 对于确定性子集可考虑决策树优化






