发布 - 订阅模式 (Publish-Subscribe Pattern, pub-sub)又叫观察者模式(Observer Pattern),它定义了一种一对多的关系,让多个订阅者对象同时监听某一个发布者,或者叫主题对象,这个主题对象的状态发生变化时就会通知所有订阅自己的订阅者对象,使得它们能够自动更新自己。
比如当我们进入一个聊天室 / 群,如果有人在聊天室发言,那么这个聊天室里的所有人都会收到这个人的发言。这是一个典型的发布 - 订阅模式,当我们加入了这个群,相当于订阅了在这个聊天室发送的消息,当有新的消息产生,聊天室会负责将消息发布给所有聊天室的订阅者。
当我们去 adadis 买鞋,发现看中的款式已经售罄了,售货员告诉你不久后这个款式会进货,到时候打电话通知你。于是你留了个电话,离开了商场,当下周某个时候 adadis 进货了,售货员拿出小本本,给所有关注这个款式的人打电话。
这也是一个日常生活中的一个发布 - 订阅模式的实例,虽然不知道什么时候进货,但是我们可以登记号码之后等待售货员的电话,不用每天都打电话问鞋子的信息。
上面两个小栗子,都属于发布 - 订阅模式的实例,群成员 / 买家属于消息的订阅者,订阅消息的变化,聊天室 / 售货员属于消息的发布者,在合适的时机向群成员 / 小本本上的订阅者发布消息。
在这样的逻辑中,有以下几个特点:
//发布者 const adadisPublish = { // 存储订阅者的一些属性信息 adadisBooks: {}, // 添加订阅,根据鞋子类型添加不同的客户订阅者信息 subscribShoe(type, customer) { if (this.adadisBooks[type]) { if (!this.adadisBooks[type].includes(customer)) { this.adadisBooks[type].push(customer); } } else { this.adadisBooks[type] = [customer]; } }, //取消订阅 unSubscribShoe(type, customer) { //取消存在的订阅者 if (!this.adadisBooks[type] || !this.adadisBooks[type].includes(customer)){ return; } const idx = this.adadisBooks[type].indexOf(customer); this.adadisBooks[type].splice(idx, 1); }, // 发布者发布消息 notify(type) { if(!this.adadisBooks[type]){ return; } this.adadisBooks[type].forEach(customer => { customer.update(type); }) } } //订阅者 const customer_one = { phoneNumer: "142xxxxx", update(type) { console.log(this.phoneNumer + ":订阅类型" + type + "updated") } } const customer_two = { phoneNumer: "158xxxxx", update(type) { console.log(this.phoneNumer + ":订阅类型" + type + "updated") } } //添加订阅 adadisPublish.subscribShoe("运动鞋", customer_one); adadisPublish.subscribShoe("运动鞋", customer_two); adadisPublish.subscribShoe("帆布鞋", customer_two); adadisPublish.notify("帆布鞋");
我们可以把上面例子的几个核心概念提取一下,买家可以被认为是订阅者(Subscriber),售货员可以被认为是发布者(Publisher),售货员持有小本本(SubscriberMap),小本本上记录有买家订阅(subscribe)的不同鞋型(Type)的信息,当然也可以退订(unSubscribe),当鞋型有消息时售货员会给订阅了当前类型消息的订阅者发布(notify)消息。
主要有下面几个概念:
原文:https://www.cnblogs.com/Nyan-Workflow-FC/p/13026629.html