一种轻量级的消息接收与响应模型
Recipient 原型是一种设计思想,用于定义对象如何接收并处理来自外部的消息或事件。 它常见于事件驱动架构、状态管理库(如 Redux 的 middleware)、以及组件通信系统中。
核心理念是:对象不主动拉取数据,而是被动“接收”(recipient)通知,并根据消息内容作出响应。
以下是一个极简的 Recipient 原型示例:
class Recipient {
constructor() {
this.handlers = {};
}
on(event, handler) {
if (!this.handlers[event]) this.handlers[event] = [];
this.handlers[event].push(handler);
}
emit(event, data) {
if (this.handlers[event]) {
this.handlers[event].forEach(fn => fn(data));
}
}
}
// 使用示例
const recipient = new Recipient();
recipient.on('greet', name => console.log(`Hello, ${name}!`));
recipient.emit('greet', 'Alice');
点击按钮发送消息,观察控制台或下方输出: