What is the observer model

We often have the need that when one object changes its behavior, its change will affect other objects, causing those objects to change accordingly.

The altered objects we call the observed objects, and the affected objects we call the observers

Take the most common chestnut

When we need to monitor mouse click events for a DOM, but we do not know when the user clicks, we need to add the corresponding event and click event binding in advance. In this case, the click event is the observation target, and the custom event we bind is the observer.

const box = document.querySelector('.box');
box.addEventListener('click'.() = >{
  console.log('box clicked one');
})
box.addEventListener('click'.() = >{
  console.log('box clicked two');
})
Copy the code

In this simple code, we add two observers to the box DOM.

How do I implement an observer pattern myself

Here we take wechat public accounts and users as cases

// Wechat official account
class WeChat {
  constructor(account){
    this.account = account
    this.observer = new Set()}addObserver(ob){
    this.observer.add(ob)
  }
  removeObserver(ob){
    this.observer.delete(ob)
  }
  pushArticles(content){
    this.observer.forEach(ob= >{
      ob.readArticles(this.account,content)
    })
  }
}
// wechat user
class Person {
  constructor(user){
    this.user = user
  }
  readArticles(article,content){
    console.log(`The ${this.user}: ${content}, from ${article}`)}}// Create a public account
const account_1 = new WeChat('The Self-cultivation of Solo')
// Create a wechat user
const user_1 = new Person('nini')
const user_2 = new Person('guapi')
// Add a user
account_1.addObserver(user_1)
account_1.addObserver(user_2)
// Push the article
account_1.pushArticles('you are good man')
account_1.removeObserver(user_1)
account_1.pushArticles("don't say something")
Copy the code

Conclusion:

  1. The observation object is stored for all observers.
  2. The observer writes the method that executes when listening.
  3. When the watch target listener event method is triggered, all observers are iterated over and the corresponding methods that the observer needs to perform are executed.

What is the publish subscribe model

Most articles refer to publish-subscribe as another name for the Observer model. Although they are very different from each other, there are differences in programming ideas.

What would happen if we wrote in a publish-subscribe model for the example above?

// The author of the public account
class WeChatAuthor {
  constructor(author){
    this.author = author
  }
  writeArticles(admin,article){
    admin.pushArticle(article)
  }
}
// wechat user
class Person {
  constructor(user){
    this.user = user
  }
  readArticles(article,wechat){
    console.log(`The ${this.user}The user read from${wechat}Article of public account:${article}`)}}/ / the public number
class WeChatAdmins {
  constructor(wechat){
    this.wechat = wechat
    this.persons = new Set()}addPerson(person){
    this.persons.add(person)
  }
  removePerson(person){
    this.persons.delete(person)
  }
  pushArticle(article){
    this.persons.forEach(person= > {
      person.readArticles(article,this.wechat)
    })
  }
}

// Apply to become an official account author
const author = new WeChatAuthor('I want a summer vacation')
// Create an official account
const wechat = new WeChatAdmins('Front End Summer Vacation Resort')
// wechat user
const person_1 = new Person('Yu Yu River')
const person_2 = new Person('Yu Yu Jiang')
// Follow the public account of 'front-end summer Vacation Resort'
wechat.addPerson(person_1)
wechat.addPerson(person_2)
// The author published the article through the public account of 'Front-end summer Vacation Resort'
author.writeArticles(wechat,'Vue3 top notch! ')

// Output result:
// You yuhe user read the article from the front of the summer vacation tourism resort public number: Vue3 top!
// You yujiang user read an article from the public number of the front-end summer vacation tourism resort: Vue3 top!
Copy the code

Observer vs. publish subscribe

Earlier we wrote the same feature case in both modes and you can see the differences between the two. Here I use words to describe, we can fine taste the difference:

  • Observer mode:The writer writes articles on the official account -> The public account is pushed to all concerned readers
  • Publish and subscribe model:The writer writes well -> Copy and paste the article into the corresponding official account -> The public account is pushed to all concerned readers

Summary of differences: Publish and subscribe mode decouples the observation target and observer to create the functional middle layer of the scheduling center. The observer is no longer directly associated with the observation target, the observer only needs to observe the scheduling center, and the change of the observation target only needs to notify the scheduling center.