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

This article will help you understand the life cycle in Vue

Table of contents 1. beforeCreate & created 2...

Nodejs combined with Socket.IO to realize websocket instant communication

Table of contents Why use websocket Socket.io Ope...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

Pure CSS3 to achieve mouse over button animation Part 2

After the previous two chapters, do you have a ne...

Gradient slide effect implemented by CSS3

Achieve results Code html <div class="css...

Detailed explanation of Object.create instance usage in js

1. Create a new object using the Object.create() ...

Vue3.0 handwriting magnifying glass effect

The effect to be achieved is: fixed zoom in twice...

Mysql specifies the date range extraction method

In the process of database operation, it is inevi...

Detailed explanation of the use of CSS3 rgb and rgba (transparent color)

I believe everyone is very sensitive to colors. C...

Import CSS files using judgment conditions

Solution 1: Use conditional import in HTML docume...

Let’s talk about the symbol data type in ES6 in detail

Table of contents Symbol Data Type The reason why...

Solution to the problem of adaptive height and width of css display table

Definition and Usage The display property specifi...

Four solutions for using setTimeout in JS for loop

Table of contents Overview Solution 1: Closures S...

JavaScript to achieve elastic navigation effect

This article shares the specific code for JavaScr...

A brief discussion on the corresponding versions of node node-sass sass-loader

Table of contents The node version does not corre...