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

Examples of using Docker and Docker-Compose

Docker is an open source container engine that he...

JS+AJAX realizes the linkage of province, city and district drop-down lists

This article shares the specific code of JS+AJAX ...

How to check if the firewall is turned off in Linux

1. Service method Check the firewall status: [roo...

Define your own ajax function using JavaScript

Since the network requests initiated by native js...

Solution to the conflict between Linux kernel and SVN versions

Phenomenon The system could compile the Linux sys...

JavaScript to implement random roll call web page

JavaScript writes a random roll call webpage for ...

Summary of Vue's cross-domain problem handling and solutions

When you send a network request, the following sa...

Detailed explanation of keepAlive usage in Vue front-end development

Table of contents Preface keep-avlive hook functi...

JavaScript single thread and asynchronous details

Table of contents 1. Task Queue 2. To explain som...

A Preliminary Study on JSBridge in Javascript

Table of contents The origin of JSBridge The bidi...

Understanding of the synchronous or asynchronous problem of setState in React

Table of contents 1. Is setState synchronous? asy...

Linux server SSH cracking prevention method (recommended)

1. The Linux server configures /etc/hosts.deny to...