A, definitions,

The observer pattern defines a one-to-many dependency that allows multiple observer objects to listen simultaneously on a subject object (notifier). The topic object notifies all observer objects when it observes a change in the observed, enabling them to update themselves

Here are a few characters and their own functions:

  1. Observer object: Can update itself
  2. Subject object: can add observer, remove observer, notify observer
  3. Observed: Monitored by the subject object, which notifies the observer to update its status when the observed changes

Two, use scenarios

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

Three, take an example

If the description of a dry concept is difficult to understand, take a common example of life to illustrate

Scenario 1:

Office building, in front of the computer. A bunch of programmers took advantage of the boss’s business trip to play NBA games on the computer, occasionally Shouting excitedly. Right now, the boss is on a business trip to come back, just touch, the scene once embarrassed.

Solution:

In order to avoid in the company water touch fish, was caught by the door of the boss, a few people think of a scheme, bribe the receptionist little sister. When the boss came back into the company, the little sister immediately informed the programmers and told them to return to work

Scenario 2:

Office building, in front of the computer. A bunch of programmers took advantage of the boss’s business trip to play NBA games on the computer, occasionally Shouting excitedly. At this time, the boss returned from a business trip. The front desk little sister saw the boss back, immediately to the little brothers watching the game notice. At this time the little brothers quickly switch to the state of work.

Scenario 2 uses the observer mode. When the boss comes back, the programmers need to change the state of the water, and the receptionist is responsible for informing them

figure role function
The programmer The observer You can change your state
Receptionist little sister Subject (Notifier) Collect, remove, and save programmers (observers) that need to be notified, and send notifications to programmers
The boss The observed Being observed by the receptionist

It is clear from the examples that each object in the observer mode and each object’s function should be distinguished. So let’s do coding

Fourth, the Coding

1. Front desk little sister class (notifier class)

/* * desc: notitioner class * 1, Store observer * 2, Add observer * 3, Remove observer * 4, notify observer */
class Dep {
    constructor() {
        // Store the observer
        this.subs = []
    }

    /** * Add observer *@param {Observer object} sub 
     */
    addSubs(sub) {
        // Make sure observers have the 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 to change its state ** / by calling the update method within all observers
    notify() {
        this.subs.forEach(sub= > {
            sub.update()
        })
    }
}
Copy the code

2. Programmer class (Observer class)

// Class constructor {constructor(name) {this.name = name} // All observer objects have their own update methods, Update () {console.log(' ${this.name} 'received notification to change working status. }} // class watcher {constructor(name) {this.name = name} // All observer objects have their own update methods. Update () {console.log(' ${this.name} 'received notification to change working status. `)}}Copy the code

3, simulate the boss back to the company, the receptionist little sister inform the programmer

 <script src="./js/Dep.js"></script>
 <script src="./js/Watcher.js"></script>
 <script>
        // My colleague Zhang SAN
        const tongshi1 = new watcher("Zhang")

        // My colleague Li Si
        const tongshi2 = new watcher("Bill")

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

        // Waiting for the boss to return....
        // etc etc....
        // etc etc....
        // etc etc....
        // etc etc....
        // The boss is back

        // When the boss returns, the foreground sister calls its notify method to notify the programmers to change their state
        xiaojiejie.notify()
    </script>
Copy the code