发布订阅模式

发布订阅模式直接没有关联,可以不发布只订阅 也可以只订阅不发布
例:

const event = {    _arr: [],    on(fn) {        this._arr.push(fn)    },    emit() {        this._arr.forEach(fn => {            fn()        })        }}event.on(() => {    console.log('数据来了')})const obj = {}event.on(() => {   if(Object.keys(obj).length == 2) {       console.log(obj)   }})obj.name = 'test'event.emit() obj.age = 12event.emit()

观察者模式

(基于发布订阅的 ,而且观察者模式发布订阅之间是有关联的)

class Subject {    constructor () {        this.state = '开心'        this.observers = []    }    attach (o) {        this.observers.push(o)    }    setState (newState) {        this.state = newState        this.observers.forEach(o => {            o.update(this)        })    }}class Observer {    update (sub) {       console.log('被观察着的状态是:' + sub.state)    }}const mama = new Observer()const baba = new Observer()const baby = new Subject()baby.attach(mama)baby.attach(baba)baby.setState('不开心')