Introduction and use of js observer mode

Introduction and use of js observer mode

Through the case, we should be able to distinguish the various objects and functions in the observer pattern. Next, coding

4. Coding

1. Front desk lady (notifier)

/*
 * desc: notifier class* 1. Store observers* 2. Add observers* 3. Remove observers* 4. Notify observers*/
class Dep {
    constructor() {
        //Storage observer this.subs = []
    }

    /**
     * Add observer * @param {observer object} sub 
     */
    addSubs(sub) {
        // Make sure all observers have update methods if (sub && sub.update) {
            this.subs.push(sub)
        }
    }

    /**
     * Remove observer * @param {observer object to be removed} sub 
     */
    removeSub(sub) {
        this.subs.forEach((item, index) => {
            if (sub.id === item.id) {
                this.subs.splice(index, 1)
                return;
            }
        })
    }

    /**
     * Notify the observer, call the update method inside all observers, and change its own state * */
    notify() {
        this.subs.forEach(sub => {
            sub.update()
        })
    }
}

2. Programmer class (Observer class)

/**
 * Observer object */
class watcher {
    constructor(name) {
        this.name = name
    }

    //Observer objects have their own update method to change their working status update() {
        console.log(`${this.name} received notification and changed working status.`)
    }
}
/**
 * Observer object */
class watcher {
    constructor(name) {
        this.name = name
    }

    //Observer objects have their own update method to change their working status update() {
        console.log(`${this.name} received notification and changed working status.`)
    }
}

3. Simulate the boss returning to the company, and the front desk lady notifies the programmer

 <script src="./js/Dep.js"></script>
 <script src="./js/Watcher.js"></script>
 <script>
        // Colleague Zhang San const tongshi1 = new watcher("Zhang San")

        // Colleague Li Si const tongshi2 = new watcher("Li Si")

        //The front desk lady needs to know which colleagues need to be notified and collect the colleagues who need to be notified const xiaojiejie = new Dep();
        xiaojiejie.addSubs(tongshi1)
        xiaojiejie.addSubs(tongshi2)

        //Waiting for the boss to return....
        // Wait, wait...
        // Wait, wait...
        // Wait, wait...
        // Wait, wait...
        //The boss is back//When the boss comes back, the front desk lady calls her own notify method to notify programmers to change their own statusxiaojiejie.notify()
    </script>

This is the end of this article about the introduction and usage background of the observer pattern in Java design pattern. For more relevant observer pattern content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement the observer pattern in JavaScript
  • js observer mode bullet screen case
  • JavaScript design pattern: observer mode and publish-subscribe mode detailed explanation
  • JavaScript Design Patterns – Observer Pattern Principles and Usage Examples
  • Simple example of observer and subscriber mode implemented in native js
  • JavaScript Observer Pattern Principles and Usage Examples
  • Teach you how to implement the observer mode in Javascript

I. Definition

The observer pattern defines a one-to-many dependency relationship, allowing multiple observer objects to monitor a subject object (notifier) ​​at the same time. When the subject object observes changes in the observed object, it notifies all observer objects so that they can update themselves.

There are several roles involved here and their own functions:

  1. Observer object: can update itself
  2. Subject object: can add observers, remove observers, and notify observers
  3. Observer: monitored by the subject object. When the observed object changes, the subject object will notify the observer to update its status.

2. Usage scenarios

When a change to one object requires changes to other objects at the same time, and there is no need to know how many objects need to be changed

3. Give an example

If the dry concept description is obscure and difficult to understand, give an example from common life to explain it

Scenario 1:

​ In the office building, in front of the computer. A bunch of programmers took advantage of their boss being away on a business trip to watch NBA games on their computers, shouting excitedly from time to time. At this moment, the boss came back from a business trip and happened to see them, creating an awkward situation.

Solution:

​ In order to avoid being caught by the boss who came in when they were slacking off in the company, a few people came up with a plan to bribe the lady at the front desk. When the boss came into the company again, the girl immediately notified the programmers and asked them to return to work.

Scenario 2:

​ In the office building, in front of the computer. A bunch of programmers took advantage of their boss being away on a business trip to watch NBA games on their computers, shouting excitedly from time to time. At this time, the boss came back from a business trip. When the lady at the front desk saw the boss coming back, she immediately notified the guys watching the game. At this time, the young men quickly switched to work mode.

Scenario 2 uses the observer pattern. When the boss comes back, the programmers need to change their paddling status, and the front desk lady is responsible for notifying them.

figure Role Function
programmer Observer Can change your status
Front desk lady Subject (notifier) Collect, remove and save programmers (observers) who need to be notified, and send notifications to programmers
boss The Observer Observed by the front desk lady

<<:  How to use bind to set up DNS server

>>:  Solution to the problem of eight hours difference in MySQL insertion time

Recommend

Vue.js implements music player

This article shares the specific code of Vue.js t...

Generate OpenSSL certificates in Linux environment

1. Environment: CentOS7, Openssl1.1.1k. 2. Concep...

mysql wildcard (sql advanced filtering)

Table of contents First, let's briefly introd...

Docker network principles and detailed analysis of custom networks

Docker virtualizes a bridge on the host machine. ...

Summary of the most commonly used knowledge points about ES6 new features

Table of contents 1. Keywords 2. Deconstruction 3...

Mysql dynamically updates the database script example explanation

The specific upgrade script is as follows: Dynami...

Solution to 1449 and 1045 exceptions when connecting to MySQL

Solution to 1449 and 1045 exceptions when connect...

Diving into JS inheritance

Table of contents Preface Prepare Summarize n way...

Bug of Chinese input garbled characters in flex program Firefox

Chinese characters cannot be input in lower versio...

Intellij IDEA quick implementation of Docker image deployment method steps

Table of contents 1. Docker enables remote access...

Implementation of setting fixed IP when starting docker container

Network type after docker installation [root@insu...

MySQL uses UNIQUE to implement non-duplicate data insertion

SQL UNIQUE constraint The UNIQUE constraint uniqu...