Introduction and Application of js Observer Mode

  • 2021-11-13 00:25:44
  • OfStack

Directory 1. Definition
2. Use scenarios
3. Give an example
4. Coding

1. Definition

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

Several roles and their own functions are involved here:

Observer object: You can update yourself Subject object: You can add observers, remove observers, and notify observers Observed: Monitor by the subject object. When the subject changes, the subject object notifies the observer to update its status

2. Use scenarios

When one object changes, it needs to change other objects at the same time, and it is not necessary to know how many objects need to be changed

3. Give an example

If the dry concept description is obscure, give a common example in life to illustrate 1

Scenario 1:

In the office building, in front of the computer. 1 pile of programmers took advantage of the boss's business trip to play NBA football game on the computer, shouting excitedly from time to time. At this time, when the boss came back from a business trip, he happened to be caught red-handed, and the scene was embarrassing for 1 degree.

Solution:

In order to avoid being caught by the boss who entered the door when paddling and fishing in the company, several people thought of a plan to bribe the little sister at the front desk. When the boss enters the company door later, the little sister immediately informs the programmers to return to work

Scenario 2:

In the office building, in front of the computer. 1 pile of programmers took advantage of the boss's business trip to play NBA football game on the computer, shouting excitedly from time to time. At this point, the boss came back from a business trip. When the little sister at the front desk saw the boss coming back, she immediately sent a notice to the little brothers watching the game. At this time, the younger brothers quickly switched to work.

Scenario 2 uses the observer mode. When the boss comes back, the programmers need to change the state of the stroke, and the little sister at the front desk is responsible for informing them

人物 角色 功能
程序员 观察者 可以改变自己的状态
前台小姐姐 主题(通知者) 收集、移除及保存需要通知的程序员(观察者),给程序员发送通知
老板 被观察者 被前台小姐姐观察

It is time to distinguish each object in the observer pattern and its function through the case. Next, coding

4. Coding

1. Miss sister at the front desk (notifier)


/*
 * desc: Notifier class 
 * 1 Store the observer 
 * 2 Add an observer 
 * 3 Remove the observer 
 * 4 Inform the observer 
 */
class Dep {
    constructor() {
        // Storage observer 
        this.subs = []
    }

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

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

    /**
     *  Notifies the observer, calling all the internal of the observer update The method of changing 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 your working state 
    update() {
        console.log(`${this.name} Change the working status after receiving the notice. `)
    }
}
/**
 *  Observer object 
 */
class watcher {
    constructor(name) {
        this.name = name
    }

    // Observer objects have their own update Method to change your working state 
    update() {
        console.log(`${this.name} Change the working status after receiving the notice. `)
    }
}

3. Simulate the boss to return to the company, and the front desk sister informs the programmer


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

        // Colleague Lee 4
        const tongshi2 = new watcher(" Li 4")

        // The little sister at the front desk 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, wait ....
        // Wait, wait, wait ....
        // The boss is back 

        // When the boss came back, the little sister at the front desk called her own notify Method informs programmers   Change one's state 
        xiaojiejie.notify()
    </script>

Related articles: