Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a publish / subscribe model with JS

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you how to use JS to write a publish and subscribe model, the content is very detailed, interested friends can refer to, hope to be helpful to you.

What is the publish and subscribe model? Can you do it by hand? Is it different from the observer model? ...

1 scene introduction

Let's first take a look at this scene:

Suppose there is a social platform with a big V called Nami.

Nami is very talented and versatile. At present, she has two skills: she can write songs and make videos.

She will publish these works on the platform. Fans who follow her will receive this content.

Now he has three fans, namely: Luffy, Zoro and Sanji

As soon as the work is published, the messages received on the accounts of the three fans will be updated.

Now use the code to represent:

Const luffy = {update: function (songs, videos) {console.log (songs, videos);},}; const zoro = {update: function (songs, videos) {console.log (songs, videos);},}; const sanji = {update: function (songs, videos) {console.log (songs, videos);},} Const nami = {/ / as soon as Nami's work is updated, this method will be called workUpdate: function () {/ / get the work const songs = this.getSongs (); const videos = this.getVideos (); / / account update luffy.update (songs, videos); zoro.update (songs, videos); sanji.update (songs, videos);}, getSongs: function () {return "mp3" , getVideos: function () {return "mp4";},}

Now here's the problem.

If Nami gains another fan Robin, I will both add a robin object and modify the workUpdate method

If Nami has a new skill: writing a novel, I have to modify both the workUpdate function and the update method in each fan object, because the parameter adds a

Did you find a problem?

The coupling between fan object and big V object is so high that it is difficult for them to expand separately.

2 Code Optimization 2.1 to solve the problem of increasing fans

Let's first solve the first problem above, so that there is no need to modify the workUpdate method when adding fans.

First of all, we abstract "Big V" into a class Star, save the fan list with array fans, and add a new method addFans to add fans.

Class Star {constructor () {this.fans = [];} addFans (fan) {this.fans.push (fan)} workUpdate () {const songs = this.getSongs (); const videos = this.getVideos (); this.fans.forEach ((item) = > item.update (songs, videos));} getSongs () {return "MP3";} getVideos () {return "MP4";}}

Next, we abstract the "fan" into a class Fan. When we create the fan object, we pass in the "big V" object and call the addFans method of the big V to add to the fan list.

Class Fan {constructor (name, star) {this.name = name this.star = star this.star.addFans (this)} update (songs, videos) {console.log (songs, videos);}}

Now that we add fans, we don't have to change the code.

Const nami = new Star () const luffy = new Fan ("luffy", nami); const zoro = new Fan ("zoro", nami); const sanji = new Fan ("sanji", nami); const robin = new Fan ("robin", nami); nami.workUpdate () 2.2 solve the problem of adding works

We add a works array to save the works of Big V, and add get and set methods to it

Class Star {constructor () {this.fans = []; this.works = [];} addFans (fan) {this.fans.push (fan);} setWorks (work) {this.works.push (work); / / after adding a work, call the update method this.workUpdate ();} getWorks () {return this.works } workUpdate () {this.fans.forEach ((item) = > item.update ());}}

Modify the class Fan accordingly:

Class Fan {constructor (name, star) {this.name = name this.star = star this.star.addFans (this)} update () {console.log (`${this.name}: ${this.star.getWorks ()}`)}}

Now that Big V adds works, you don't have to change the code:

Const nami = new Star (); nami.setWorks ('song') nami.setWorks (' video') nami.setWorks ('novel') const luffy = new Fan ("luffy", nami); const zoro = new Fan ("zoro", nami); const sanji = new Fan ("sanji", nami); nami.workUpdate (); 3 Observer mode

As you can see, in the above example, there is an one-to-many dependency between a nami object and multiple fan objects, and when the nami object has a work update, all fans who follow her will be notified.

In fact, this is the observer model.

Observer pattern: defines an one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and updated automatically.

We further abstract the code in 2.2:

Regarding the "fan" as the Observer and the "Big V" as the observed object, it is called the Subject.

Subject maintains an observer list observerList (formerly the fans array). When the state of the Subject changes (the original work is updated), notify all observers by calling the notify (original workUpdate) method to execute their update method

The specific code is as follows:

/ / observed: topic class Subject {constructor () {this.observerList = []; / represents topic status this.state = 0;} addObserver (observer) {this.observerList.push (observer);} / / change topic status setState (state) {this.state = state; / / notify all observers after the state changes } getState () {return this.state;} notify () {this.observerList.forEach ((observer) = > observer.update ());}} / / Observer class Observer {constructor (name, subject) {this.name = name; this.subject = subject; this.subject.addObserver (this);} update () {console.log (`${this.name}: ${this.subject.state}`);}} 4 broker debut

Due to the busy business of Big V, they need agents to maintain the connection between artists and fans.

The work of a broker includes:

Maintain the fans of Big V, the agent will have a fan list.

The new work of Big V will be handed over to the agent, who will be responsible for sending the new work to the fans on the fan list.

Abstracted into a class, as follows:

Class Manager {constructor () {this.fans = []; this.works = [];} addFans (fan) {this.fans.push (fan);} setWorks (work) {this.works.push (work); / / after adding a work, call the update method this.workUpdate ();} getWorks () {return this.works } workUpdate () {this.fans.forEach ((item) = > item.update ());}}

Yeah? Where has this code been seen before?

Yes, it's exactly the same as the Star class in 2.2, except that the name of the class has been changed.

Does that make sense?

In fact, the code is exactly the same because we only write about publishing (that is, publishing works) and subscriptions (that is, maintaining fan lists) in the Star class of 2.2; the Star class itself may do more than that, such as authoring content.

Now let's take the publishing and subscribing work out of the Star class and leave it to Manager. On the other hand, the Star class only needs to give the work to Manager after the creation is completed.

On the other hand, fan Fan no longer interacts directly with Star. Fan only cares about receiving the work, so Fan interacts directly with Manager, and Fan subscribes to Manager (which is equivalent to adding fans to the fan list maintained by Manager) and gets the desired work from Manager.

So the code for Star and Fan is as follows:

Class Star {constructor () {} / Creative create (manager) {/ / hand the created new work to the broker manager.setWorks ("new work");}} class Fan {constructor (name, manager) {this.name = name; this.manager = manager; this.manager.addFans (this);} update () {console.log (`${this.name}: ${this.manager.getWorks ()}`) 5 publish and subscribe model

Earlier, we used brokers to be responsible for publishing and subscribing, without allowing Star and Fan to interact directly, thus achieving the effect of decoupling the two.

This is the publish and subscribe model.

Let's further abstract the Manager in 4:

Think of "fans" as Subscriber; regard "Big V" as the publisher of content, which is called Publisher in publish-subscribe model; regard "broker" as publish-subscribe center (or middleman Broker)

The specific code is as follows:

/ / publish and subscribe scheduling center class Broker {constructor () {this.subscribers = []; / / represents topic status this.state = 0;} / subscribe to subscribe (subscriber) {this.subscribers.push (subscriber);} / / change topic status setState (state) {this.state = state; / / publish this.publish () after the status changes } getState () {return this.state;} / / publish publish () {this.subscribers.forEach ((subscriber) = > subscriber.update ());} / / publisher class Publisher {constructor () {} changeState (broker, state) {broker.setState (state);}} class Subscriber {constructor (name, broker) {this.name = name; this.broker = broker; this.broker.subscribe (this) } update () {console.log (`${this.name}: ${this.broker.getState ()}`);}}

Let's run it and see how it works:

/ / create the scheduling center const broker = new Broker () / / create the publisher const publisher = new Publisher () / / create the subscriber const subscribe1 = new Subscriber ('s 1 subscription, broker) const subscribe2 = new Subscriber ('s 2 minutes, broker) const subscribe3 = new Subscriber ('s 3 minutes, broker) / / the publisher changes the state and notifies the scheduling center, and the scheduling center notifies each subscriber of the comparison between publisher.changeState (broker, 1) 6 Observer mode and publish subscription mode

In terms of the number of roles

The observer model has only two roles: the observer and the observed.

The publish-subscribe model has three roles: publisher, subscriber, and middleman (publish and subscribe center)

In terms of the degree of coupling

The observer mode is in a loosely coupled state, that is, the two still interact, but it is easy to expand and not influence each other.

In the publish-subscribe model, there is no coupling between publishers and subscribers, which achieves the effect of decoupling between objects.

From the perspective of intention

Both: an one-to-many dependency between objects is realized. when the state of an object changes, all objects that depend on it will be notified and updated automatically

On how to use JS to write a publish and subscribe model to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report