发布-订阅模式
定义
发布-订阅模式又称观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都将得到通知。在 Javascript 开发中,我们一般用事件模型来替代传统的发布订阅模式。
作用
1.发布-订阅模式可以广泛应用于异步编程中,这是一种替代传统回调函数的方案。比如,我们可以订阅 ajax 请求的 error、success 等事件。或者如果想在动画的每一帧完成之后做一些事情,那我们可以订阅一个事件,然后在动画的每一帧完成之后发布这个事件。在异步编程中使用发布-订阅模式,我们就无需过多关注对象在异步运行期间的内部状态,只需要订阅感兴趣的事件发生点。
2.发布-订阅模式可以取代对象之间硬编码的通知机制,一个对象不用再显式地调用另一个对象的某个接口。发布-订阅模式让两个对象松耦合的联系在一起。当有新的订阅者出现时,发布者的代码不需要任何修改;同样发布者需要改变时,也不影响到之前的订阅者。只要之前约定的事件名没有变化,就可以自由地改变它们。
实例
// 定义发布者(商品店)
const shop = {
// 登记在册的顾客
customers: [],
// 顾客订阅指定商品
addCargo(customer, type) {
if(!this.customers.includes(customer)) {
this.customers.push(customer);
}
customer.order.push(type);
console.log(customer.name + "订阅商品" + type);
},
// 顾客取消订阅指定商品
delCargo(customer, type) {
if(this.customers.includes(customer)) {
const idx = customer.order.indexOf(type);
if(idx > 0) {
customer.order.splice(idx, 1);
console.log(customer.name + "取消订阅商品" + type);
} else {
console.log(customer.name + "未订阅商品" + type);
}
} else {
console.log("顾客不存在。")
}
},
// 顾客不在订阅任何商品
delCustomer(customer) {
if(this.customers.includes(customer)) {
const idx = this.customers.indexOf(customer)
this.customers.splice(idx, 1);
} else {
console.log("顾客不存在。")
}
},
// 通知顾客订阅的商品有货
notify(type) {
for (const customer of this.customers) {
const idx = customer.order.indexOf(type);
if(idx >= 0) {
customer.update(type);
}
}
}
}
// 定义订阅者(顾客)
const customer1 = {
name: 'xiaoming',
// 顾客订阅的商品
order: [],
update(type) {
console.log(this.name + '去商场看看订购的商品'+ type)
}
}
const customer2 = {
name: 'xiaohong',
order: [],
update(type) {
console.log(this.name + '去商场看看订购的商品' + type)
}
}
shop.addCargo(customer1,"鞋子") // 小明订阅鞋子
shop.addCargo(customer1,"雨伞") // 小明订阅雨伞
shop.addCargo(customer2,"雨伞") // 小红订阅雨伞
shop.addCargo(customer2,"衣服") // 小红订阅衣服
shop.notify("雨伞") // 通知所有顾客雨伞已到货
shop.notify("鞋子") // 通知所有顾客鞋子已到货
shop.delCargo(customer1, "雨伞"); // 小明已买到雨伞,不再订阅雨伞
shop.notify("雨伞") // 再次通知雨伞已到货
打印结果展示:
xiaoming订阅商品鞋子
xiaoming订阅商品雨伞
xiaohong订阅商品雨伞
xiaohong订阅商品衣服
xiaoming去商场看看订购的商品雨伞
xiaohong去商场看看订购的商品雨伞
xiaoming去商场看看订购的商品鞋子
xiaohong去商场看看订购的商品雨伞
总结
发布-订阅模式的优点非常明显,一为时间上的解耦,二为对象之间的解耦。它的应用非常广泛,既可以用在异步编程中,也可以帮助我们完成更松耦合的代码编写。
当然,发布-订阅模式模式也不是完全没有缺点。创建订阅者本身需要消耗一定的时间和内存,而且当你订阅一个消息后,也许此消息最后都未发生,但这个订阅者会始终存在于内存中。另外,发布-订阅模式虽然可以弱化对象之间的联系,但如果过度使用的话,对象和对象之间的必要联系也将深埋在背后,会导致程序难以维护和理解。特别是有多个发布者和订阅者嵌套到一起的时候,要跟踪一个 bug 不是件轻松的事情。