订阅者发布模式与观察者模式

89 阅读1分钟

1.订阅者发布模式

class Pubsub{
  constructor(){
    this.events = {}
  }

  subScribe(type,cb){
    if(!this.events[type]){
      this.events[type] = []
    }
    this.events[type].push(cb)
  }

  unSunScribe(type,cb){
    if(this.events[type]){
      const findIndex = this.events[type].findIndex((callback)=>{
        return callback == cb
      })
      this.events[type].splice(findIndex,1)
    }
    if(!this.events[type].length){
      delete this.events[type]
    }
  }

  publish(type,...arg){
    this.events[type].forEach(cb => {
      cb(...arg)
    });
  }


}

let pub = new Pubsub()
pub.subScribe("学习",(arg)=>{
  console.log(arg)
})

pub.subScribe("学习",(arg)=>{
  console.log("继续学习",arg)
})

pub.publish("学习","p1学习前端知识")
pub.publish("学习","jjjjj")
// pub.publish("学习","学习计算机网络")

2.观察者模式

class Observe{
  constructor(cb){
    if(typeof(cb) !="function"){
      this.cb = cb;
    }else{
      throw Error("观察者为一个函数")
    }
  }

  updata(){
    this.cb()
  }
}

class Subject{
  constructor(){
    this.obserbeList = []
  }

  addObserve(observe){
    this.obserbeList.push(observe)
  }

  notify(){
    this.obserbeList.forEach(observe=>{
      observe.notify()
    })
  }
}