Article series

Javascript design pattern singleton pattern

The adaptor pattern of javascript design patterns

The Decorator pattern of javascript design patterns

Proxy mode of javascript design pattern

Comparison of javascript adaptation, proxy, and decorator patterns

State mode of javascript design mode

The iterator pattern of javascript design patterns

Policy mode of javascript design pattern

The Observer pattern of javascript design patterns

Publish subscriber mode of javascript design pattern

What is the observer mode

Observer mode

The observer pattern defines a one-to-many dependency in which multiple observer objects listen to a single target object at the same time. When the target object’s state changes, all observer objects are notified so that they can be updated automatically. – Graphic Design Patterns

The observer pattern in life

Xiao Ming recently took a look at a real estate, to the sales office was told after the house has not opened, the specific opening time has not been set. In addition to Xiao Ming, together with Xiao Hong, two people, in order to the first time that the opening time of the building, they left their phone number to the salesman Wang Wu, Wang Wu also promised that the opening of the building will send a message to inform them.

After a while, the opening time of the new building was fixed, Wang Wu hurriedly took out the roster, traversed the number above, group sent a text message to inform them.

It was up to these people to decide whether they would walk, drive or not

Key concepts:

The observer pattern has an alias called the published-subscribe pattern (there are some differences between the two, let’s see). This alias very vividly illustrates the two core role requirements in the observer pattern: publisher and subscriber. Fit this case in your life as follows:

Posted by: Wang Wu

Subscribers: Xiao Ming, Xiao Hong, Xiao Er

Subscription event: Xiao Ming, Xiao Hong, Xiao er will leave their numbers in the sales department

Notifying changes: Wang Wuqun sends text messages to notify them

Custom observer mode

From the above analysis, the pattern creates two classes, one to represent the publisher, named Subject, and the other to represent the subscriber, named Observer. What should this class do? What is the operation of the king above?

  • Register the number of Xiao Ming, Xiao Hong and Xiao Er (add subscribers)
  • Group text message via Xiao Ming, Xiao Hong, Xiao Er (notify subscribers)
  • In addition, as a salesman, I should also have the permission to delete some people (for example, Xiaoming replied that he had not bought any more, then I can consider deleting him from the roster).

Based on the above analysis, write the following code:

// Define the publisher class
class Subject {
  constructor() {
    this.observers = []
    console.log('Subject created')}// Add subscribers
  add(observer) {
    console.log('Subject.add invoked')
    this.observers.push(observer)
  }
  // Remove subscribers
  remove(observer) {
    console.log('Subject.remove invoked')
    this.observers.forEach((item, i) = > {
      if (item === observer) {
        this.observers.splice(i, 1)}}}// Notify all subscribers
  notify() {
    console.log('Publisher.notify invoked')
    this.observers.forEach((observer) = > {
      observer.update(this)}}}Copy the code

Let’s take a look at the functions that subscribers have. What does Xiao Ming have?

  • To be informed of the opening of the building
// Define the subscriber class
class Observer {
    constructor() {
      console.log('Observer created')}update() {
      console.log('Observer.update invoked')}}Copy the code

The two classes defined above are the most basic observer pattern. In real business development, customized publishers/subscribers can inherit both of these basics to extend. For example, now there is a demand to monitor the change of the opening or not. The code is as follows:

// Define a specific sales release class
class SalesPublisher extends Subject {
	constructor() {
		super(a)// The building was not opened at first
		this.state = 'close'
		// The person number has not been registered
		this.observers = []
	}
	// Get the current building status
	getState() {
		return this.state
	}
	// Set the status of the building
	setState(state) {
		console.info('The building is open')
		this.state = state
		// If the status of the building changes, notify the people who want to buy the house
		this.notify()
	}
}
Copy the code

As a homebuyer

// Purchase subcategory
class BuyerObserver extends Observer {
	constructor(name) {
		super(a)this.name = name
	}

	// Override a specific update method
	update(publisher) {
		// Get the status of the building
		let state = publisher.getState()
		console.info(`The ${this.name} update, state: ${state}`)
		this.doSomething()
	}
	// After receiving the message, the subsequent logic to deal with, such as reply sales received, start to raise money, etc
	doSomething() {
		console.info('Start raising money')}}Copy the code

Now, let’s check to see if this code works. What is normal: when the state of the building changes, will immediately call the notify method to notify all home buyers, also realize the definition of the so-called:

All observer objects are notified when the state of the target object changes, enabling them to update automatically.

// Create subscriber: Xiao Ming
const xiaoMing = new BuyerObserver('Ming')
// Create subscriber: xiaohong
const xiaoHong = new BuyerObserver('little red')
// Create subscriber: minor 2
const xiaoEr = new BuyerObserver('small 2')

// Created by: Wang Wu
const wangwu = new SalesPublisher()

// Start adding home buyers' numbers
wangwu.add(xiaoMing)
wangwu.add(xiaoHong)
wangwu.add(xiaoEr)

// The building is open. It's time to inform the buyers
wangwu.setState('open')
Copy the code

Above, is an observer pattern implementation process

Refer to the link

Core principles and application practices of JavaScript design pattern

conclusion

The next post will cover the publish-subscriber model. Your “like” is my biggest affirmation, if you think it is helpful, please leave your praise, thank you!!

In this paper, the code