定义:发布/订阅的原理类似于观察者模式。它们都定义了一对多的依赖关系。当相关状态更新时,会触发相应的更新。本文代码执行过程与流程图基本相同(本文只是为了加深理解,不添加取消订阅等)//publisherfunctionPublish(){this.themes=[]//添加this.setCol=function(theme){this.themes.push(theme)}//主题更新this.public=function(theme){const{themes}=thisfor(leti=0;i{item.updated(callback)})}}//订阅者乐趣actionSubscrib(name){this.name=namethis.updated=function(callback){console.log(`${this.name}收到一条新消息`,callback(this.name))}}constsub1=newSubscrib('订阅者1')constsub2=newSubscrib('订阅者2')consttheme1=newTheme('三国志',(e)=>e)consttheme2=newTheme('楚汉',(e)=>e)constpublish=newPublish('Publisher')publish.setCol(theme1)publish.setCol(theme2)theme1.setSub(sub1)theme2.setSub(sub1)theme2.setSub(sub2)publish.public(theme1)/*发布者触发三国主题更新三国主题触发更新订阅者1收到新消息订阅者1*/publish.public(theme2)/*发布者触发楚汉主题更新楚汉主题触发更新订阅者1收到新消息订阅者1订阅者2收到新消息订阅者2*/