“This is the second day of my participation in the First Challenge 2022.

preface

The observer mode and the publish and subscribe mode are often used in daily development, but packages have not been well distinguished. A few days ago, when LISTENING to handwritten Promise source code, the teacher explained the two modes in detail, and found it was still difficult to understand.

It’s better to catch it early than catch it. Recently, the small package is just using the wuxia wind to read JavaScript. The wuxia world can really give JavaScript a different charm.

The story background

Since the release of the inheritance scheme, the front-end Clan gate has become increasingly prosperous and the level of its disciples has been constantly improving, but a new problem has emerged — a serious shortage of high-quality tasks. The door task hall released every month of the five star task is limited, want to take the five star task of the disciple but such as crucian carp across the river, so the breeding of the wuxia scalper, malicious grab task, sit to start.

Zongmen do not want tasks to be maliciously robbed, decided to adjust the task market order, so launched the task subscription function – observer mode.

Observer model

The general function of mission subscription is as follows: the clan launched the five-star mission subscription function, and disciples bought the subscription permission. When the clan released the five-star mission, the disciples with the subscription permission would be notified.

There are two types of subjects in the task subscription function:

  • Zong Gate mission Hall
    • Maintains a list of disciples that have subscription privileges
    • Provides the ability for disciples to purchase subscription permissions
    • Inform disciples with subscription permission after Posting tasks
  • The disciples who received the mission announcement

The relationship between the mission hall and the disciples above constitutes an observer model.

What is the observer model? When there is a one-to-many dependency between objects, the state of one object changes and all dependent objects are notified. This is the observer pattern.

In the Observer mode, there are only two types of subjects: Object and Observer. The main hall of dzongmen mission is the target, and the disciples are the observers.

  • The target objectSubject:
    • Maintain a list of observersobserverList———— maintains a list of disciples that have subscription privileges
    • Define methods for adding observers ———— provides the ability for disciples to purchase subscription permissions
    • When itself changes, by calling its ownnotifyMethod instructs each observer in turn to executeupdateMethod ———— notifying disciples with subscription permission after publishing corresponding tasks
  • The observerObserverYou need to implementupdateMethod to be called by the target object.updateMethods in which custom business logic can be performed ———— disciples need to define methods for receiving task notifications, such as going to grab a task or continuing to wait for the next task if the task is not suitable

Let’s visualize the words above:

class Observer {
    constructor(name) {
        this.name = name;
    }
    update({taskType, taskInfo}) {
        // Assume tasks are divided into daily route and combat WAR
        if (taskType === "route") {
            console.log(`The ${this.name}No daily tasks are required);
            return;
        }
        this.goToTaskHome(taskInfo);
        
    }
    goToTaskHome(info) {
        console.log(`The ${this.name}To the mission Hall${info}Task `); }}class Subject {
    constructor() {
        this.observerList = []
    }
    addObserver(observer) {
        this.observerList.push(observer);
    }
    notify(task) {
        console.log("Publish a five-star mission.");
        this.observerList.forEach(observer= > observer.update(task))
    }
}

const subject = new Subject();
const stu1 = new Observer(Disciple "1");
const stu2 = new Observer("Disciples 2");

// stu1 stu2 Purchase the permission to notify 5-star tasks
subject.addObserver(stu1);
subject.addObserver(stu2);

// The quest palace releases 5-star combat missions
const warTask = {
    taskType: 'war'.taskInfo: "Time to Kill."
}

// The office hall informed the disciple to purchase permission
subject.notify(warTask);

// The task hall publishes 5-star daily tasks
const routeTask = {
    taskType: 'route'.taskInfo: "Plant trees and water them"
}

subject.notify(warTask);

Copy the code

Output result:

// Combat missionsRelease 5-star mission disciple1Go to the mission hall to hunt down mission disciples2Go to the Mission Hall for the Hunt and kill mission// Daily tasksRelease 5-star mission disciple1Go to the mission hall to hunt down mission disciples2Go to the Mission Hall for the Hunt and kill missionCopy the code

As we can see from the code above, when a mission is published by the clan, the subscribed disciples (observers) receive the latest notification of the mission.

See here, I wonder if you can understand the observer mode?

For example, if you want to apply for the position of alibaba’s front-end engineer, the result of Alibaba HR tells you that there is no vacancy, leave your phone number and wait for the vacancy to contact you. So, you happily left the contact information. Little do they know, HR has left a lot of contact information. Fortunately, on February 30, 2022, Alibaba had the position of front-end engineer, and HR contacted with the contact information left by him.

In this case, Alibaba is the target object Subject, and the contact list is the observerList used to maintain the observer. The notify method is called according to the presence or absence of the front-end position.

Publish and subscribe

As mentioned above, the quest Hall provides a five-star quest subscription function, but there are several problems with the function:

  • Task types are not clearly divided. For example, some disciples only need 5-star combat tasks, some only need 5-star daily tasks, and some need all tasks.
  • The coupling between disciples and the mission hall of dzongmun is very high

Face so multifarious problem, wuxia intermediary company should be born however. After the birth of the intermediary company, disciples did not have to deal directly with the Main hall of Dzongmen tasks. So now there are three types of subjects:

  • Zong Gate mission Hall: Mission publisher
  • Intermediary company
    • Maintain the task type list
    • Provides the subscription task functionsubscribe: Disciples can subscribe to combat missions or daily missions
    • Provides task publishing functionpublish: Issue combat missions or daily missions to disciples
  • The disciples who received the mission

Dzongmen mission hall, intermediary companies, disciples constitute a publish and subscribe model.

So what is publish-subscribe? Publish subscription mode refers to that the Subscriber that wants to receive notification subscribes to a topic by custom event, and the Publisher notifies the Subscriber objects that subscribe to the topic by publishing the topic event.

There are three roles in the publish and subscribe mode: Publisher, Event Channel and Subscriber.

  • Publishers and subscribers are loosely coupled and do not care if each other exists ———— There is no coupling between dzongmen mission halls and disciples, linked through intermediary companies
  • Publishers just publish missions ———— zong Gate mission hall
  • Subscribers just accept the mission ————— the disciples of the mission
  • Event Dispatch center ———— Intermediary company
    • Object of a maintenance task event ———— List of maintenance task types
    • Provide subscription function to subscribers ———— provide subscription task functionsubscribe
    • Publishing event information to subscribers ———— provides task publishing functionpublish

class PubSub {
    constructor() {
        // Event center
        // Storage format: warTask: [], routeTask: []
        // Each event (task) holds its subscriber callback function
        this.events = {}
    }
    // Subscribe method
    subscribe(type, cb) {
        if (!this.events[type]) {
            this.events[type] = [];
        }
        this.events[type].push(cb);
    }
    // Publish method
    publish(type, ... args) {
        if (this.events[type]) {
            this.events[type].forEach(cb= >cb(... args)) } }// Unsubscribe method
    unsubscribe(type, cb) {
        if (this.events[type]) {
            const cbIndex = this.events[type].findIndex(e= > e === cb)
            if(cbIndex ! = -1) {
                this.events[type].splice(cbIndex, 1); }}if (this.events[type].length === 0) {
            delete this.events[type]; }}unsubscribeAll(type) {
        if (this.events[type]) {
            delete this.events[type]; }}}// Create an intermediary
let pubsub = new PubSub();

// Disciple 1 subscribed to the battle mission
pubsub.subscribe('warTask'.function (taskInfo){
    console.log("Zong Gate Temple issued combat mission, mission information :" + taskInfo);
})
// Disciple 1 subscribed to the battle mission
pubsub.subscribe('routeTask'.function (taskInfo) {
    console.log("Zong Mendian daily mission, mission information :" + taskInfo);
});
// Disciple 3 subscribes to all types of quests
pubsub.subscribe('allTask'.function (taskInfo) {
    console.log("Zongmendian issued a five-star mission, mission information :" + taskInfo);
});

// Release combat missions
pubsub.publish('warTask'."Time to Kill.");
pubsub.publish('allTask'."Time to Kill.");

// Publish daily tasks
pubsub.publish('routeTask'."Plant trees and water them");
pubsub.publish('allTask'."Plant trees and water them");
Copy the code

Output result:

// Combat missionsDzongmen Palace released the battle mission, mission information: Hunting time dzongmen Palace released the five-star mission, mission information: hunting time// Daily tasksZongmen Palace released daily tasks, mission information: plant trees and water Zongmen Palace released 5-star missions, mission information: plant trees and waterCopy the code

From the output, we can see that the publisher and the subscriber are unaware of each other’s existence. A third party mediator is required to connect subscribers and publishers, using the mediator to filter and distribute all incoming messages. That is, the publish-subscribe pattern is used to handle the exchange of information between different system components, even if they are unaware of each other’s existence.

conclusion

The observer model and the publish-subscribe model were mentioned above, so let’s summarize the differences:

Design patterns Observer model Publish and subscribe model
The main body Object Observer, Subject Target Object Publisher, Event Channel, And Subscribe
Main body relations The ObServer is logged with observerList in Subject Publisher and Subscribe do not want to know each other, and contact through intermediary
advantages The roles are clear, and Subject and Object follow the conventions of member methods Loose coupling, high flexibility, commonly used in asynchronous programming
disadvantages Tightly coupled When the number of event types increases, maintenance costs increase
Use case Two-way data binding EventBus

Hot article recommended

  • Spend the Spring Festival of the particle animation to remember your words | support expression
  • Rotation, the React! — Dancing React icon
  • Super decompression, to achieve particle gravitation and repulsion effect

Past wonderful articles

  • Cow guest latest front-end JS written test 100 questions
  • The latest front end of the interview questions summary (including analysis)
  • CSS to achieve a free flying bird 🐦
  • Happy cat stroking for VSCode and website adoptive cats
  • Native JavaScript soul Test (1), how much can you answer?
  • A thorough understanding of prototypes and prototype chains in JavaScript
  • Complete understanding of EventLoop in JavaScript
  • “2W word big chapter 38 interview questions” completely clear JS this pointing to the problem

Refer to the link

  • Talk about publish subscribe and observer model from an interview question
  • Observer vs. publish-subscribe

After the language

Guys, if you find this article helpful, give a like to 👍 or follow ➕ to support me.

In addition, if this article has a question, or do not understand part of the article, you can reply to me in the comment section, we come to discuss, learn together, progress together!

An early end to the epidemic will restore peace to the world