发布订阅模式
发布订阅模式(Publish-Subscribe Pattern)是一种常见的设计模式,用于实现消息的发布和订阅。在这种模式中,发布者发布消息,而订阅者则订阅感兴趣的消息,并在消息发布时接收通知。
特点
- 解耦:发布者和订阅者之间是松耦合的关系,彼此不需要知道对方的具体实现细节。这有助于提高系统的灵活性和可扩展性。
- 实时通信:支持实时消息传递,对于需要及时更新的应用场景非常有用,如实时数据监控、警报系统等。
- 多对多通信:一个发布者可以向多个订阅者发送消息,同时一个订阅者也可以订阅多个发布者的消息,实现了多对多的通信。
- 可扩展性:易于扩展,新的订阅者可以随时加入,而不需要修改现有系统的结构。
- 消息过滤:订阅者可以根据自己的需求订阅特定类型的消息,实现消息的过滤和个性化。
- 异步处理:发布者发送消息后不需要等待订阅者的处理结果,可以继续其他工作,提高了系统的效率。
JS简单实现
class EventPush {
constructor(props) {
this.observer = {}
}
publish(name, fn) {
if (!this.observer[name]) {
this.observer[name] = []
}
console.log('订阅事件', name, fn.name)
this.observer[name].push(fn);
}
notice(name, ...reset) {
if (!this.observer[name]) {
console.log('为订阅当前事件!')
return;
}
this.observer[name].forEach(f => f(...reset))
}
unsubscribe(name, fn) {
if (!this.observer[name]) {
console.log('未订阅当前事件!')
return;
}
const index = this.observer[name].findIndex(f => f == fn);
if (index != -1) {
this.observer[name].splice(index, 1)
}
}
}
const eventsP = new EventPush();
function say(...reset) {
console.log('say', reset)
}
eventsP.publish('say', say)
eventsP.publish('say', function (...reset) { console.log('ddd', reset) }) // 匿名函数无法取消
eventsP.notice('say', 'zhangsan')
eventsP.unsubscribe('say', say) // 具名函数可以取消订阅
eventsP.notice('say', 'zhangsan')