JavaScript implements observer mode and publish-subscribe mode

Observer pattern and publish-subscribe pattern

Observer pattern

The observer directly subscribes to the topic, and when the topic is activated, an event in the observer will be triggered.

The subject creates an array to hold the observers

The observer creates a function to wait to be triggered, and the subject creates a function to change the state. Once the state changes, it traverses each observer to execute the response function inside.

// 观察者模式
// 主题Subject
class Subject{
    
    
  constructor(name){
    
    
    //小宝宝状态
    this.name = name
    this.state = '开心'
    this.observer = [] //存放观察者
  }
  // 将观察者存在observer数组
  attach(ther){
    
    
    this.observer.push(ther)
  }
  // 主题变化后,通知观察者变换状态
  setState(state){
    
    
    this.state = state
    // 循环取出每个观察者
    this.observer.forEach(ther=>{
    
    
      ther.update(this)
    })
  }
}

// 观察者Observer
class Observer{
    
    
  constructor(name){
    
    
    this.name = name
  }
  // 观察主题状态
  update(subject){
    
    
    console.log(this.name+':'+subject.name+'当前状态是'+subject.state);
  }
}

let baby = new Subject('小宝宝')

let father = new Observer('爸爸')
let mother = new Observer('妈妈')

baby.attach(father)
baby.attach(mother)

baby.setState('不开心')
baby.setState('非常开心')

Publish Subscriber Pattern

Subscribers register the events they want to subscribe to the dispatch center, and the publisher publishes the event, that is, when the event is triggered, the dispatch center uniformly dispatches subscribers

Subscribe with on, publish with emit

// 订阅者模式
// 邮局(调度中心)
let e = {
    
    
  // 存订阅者
  _callback:[],
  on(callback){
    
    
    this._callback.push(callback)
  },
  // 发布者
  emit(value){
    
    
    this._callback.forEach(method=>{
    
    
      method(value)
    })
  }
}
// 订阅
e.on(function(value){
    
    
  console.log("张三订阅:"+value);
})
// 订阅
e.on(function(value){
    
    
  console.log("李四订阅:"+value);
})
// 订阅
e.on(function(value){
    
    
  console.log("王五订阅:"+value);
})

// 发布
e.emit('中央日报')

Guess you like

Origin blog.csdn.net/qq_47234456/article/details/128863568