网上的大部分例子有些太官方,说实在的有点很差理解,说下我的粗浅看法javascript
这是一个女神和备胎们的故事java
class Girl { constructor() { this.backupList = [] // 备胎列表 } add(person) { // 加入备胎 this.backupList.push(person) } remove(person) { // 踢出备胎 let index = this.backupList.findIndex(item=>item===person) index > -1 && this.backupList.splice(index,1) } sendMsg(msg) { // 给备胎发消息 for(let o of this.backupList) { o.update(msg) } } } class Person { constructor(name) { this.name = name // 备胎的名字 } update(msg) { // 备胎收到女神的消息 console.log(`我是${this.name},女神给我说:${msg}`) } } let lisa = new Girl() let person1 = new Person('阿天') let person2 = new Person('阿狗') lisa.add(person1) lisa.add(person2) lisa.sendMsg('我想有个家')
女神Lisa的角色就是一个“观察者”,她发现她中奖了,因此发了消息给备胎们this
优势: 一对多,下降耦合
这是一个相亲机构的故事code
let agent = { list: {}, // 订阅者容器 on(key, fn) { // 添加订阅者 if(!this.list[key])this.list[key] = [] this.list[key].push(fn) }, off(key,fn){ // 移除订阅者 let fnList = this.list[key] if(!fnList)return if(!fn) { // 若是没有具体的订阅者,则移除所有 fnList.length = 0 }else { fnList.forEach((item,index) => { item === fn && fnList.splice(index,1) }) } }, trigger(key, ...args) { // 发布 for(let fn of this.list[key])fn.call(this,...args) } }
知识点: 此时出现了“字面量模式”
此时有两位男士订阅了该机构,关键词分别是“年轻”和“好身材”事件
agent.on('young',info=>{ console.log(`有一个新发布:姓名:${info.name},年龄:${info.age}`) }) agent.on('body',info=>{ console.log(`有一个新发布:姓名:${info.name},胸围:${info.bust}`) })
又有两位女士来到该机构发布了她们的信息ip
agent.trigger('young',{ name: '圆圆', age: '18' }) agent.trigger('body',{ name: '希希', bust: '88' })
同时,两位订阅的男士就收到了发布的信息rem
有一个新发布:姓名:圆圆,年龄:18 有一个新发布:姓名:希希,胸围:88
优势: 多对多,耦合更低
on,off,trigger不就是Jquery中绑定事件嘛,因此它就是典型的发布订阅模式
发布订阅模式比观察者模式多了一个中间层,耦合更低,项目越大,优点就更明显,并且这个中间层还能提取出来做为一个单独的文件写各类操做it