“The Man in the Bureau” this TV series believe that many people have seen, we take “The Man in the Bureau” as an example, explain the observer mode and publish and subscribe mode. The Observer model and the publish-subscribe model can be a bit esoteric if you just look at the concept, so this article will try to make it as simple as possible.

Observer model

What is the observer model? Conceptually, the observer pattern is an object that maintains multiple dependent objects, and when the associated states of the object change, the dependent objects update and obtain those states.

Bureau middleman in, shen Lin of director of bureau is mixed its younger brother Shen fang is close brother, because of such, Shen Lin wants to know urgently shen Fang is underground party after all. As a result, Shen Lin dispatched intelligence officers to track Shen Fang around the clock. So, in terms of the observer model, intelligence personnel belong to the observer, and Shen Fang is the observed object.

SubType class, also refers to the tracking monitoring of the shen Fang

This. State = null // Observers = [] // observers, // Add an observer, that is, at any time other intelligence personnel may join in the action of monitoring the release of the addObserver(... args){ this.observers.concat(... Args)} // removeObserver(observer) {if (! observer) { return } let index = this.observers.findIndex(item => item === observer) this.observers.splice(index, SetState (action){// When Shen Fang has any new action, getInfo will be automatically called. GetInfo (action){this.state = action this.getInfo(action) {this.state = action this.getInfo(action)} This. Observers. ForEach (item => {item.update((name) => {console.log(' ${name}} monitor: ${this.name} -> ${action} ')})})}}Copy the code

Next look at the observer object:

Observer class

Class Observer {constructor(name){constructor(name){callback (callback){callback?.(this.name)}}Copy the code

Three intelligence agents were dispatched

Let P1 = new Observer(' 1') let P2 = new Observer(' 2')Copy the code

Commence observation of target mission. – Echo

AddObserver (P1) info.addobServer (P2) info.addobserver (P3)Copy the code

Next, some of shen Fang’s actions will be picked up by intelligence agents

Info.setstate (' went out in the morning straight to the central bureau of Statistics ') info.setstate (' went to lunch with the daughter of the bank president ') info.setstate (' went to the Gate of Joy to drink in the evening, did not come back all night ')Copy the code

Take a look at the console print:

Surveillance situation of intelligence officer 1: The target - Shen Fang -> went out in the morning and directly went to intelligence officer 2 of The Central Statistical Bureau of China. Target - Shen Fang -> had lunch with the daughter of the bank president at noon intelligence Officer 2 Surveillance: Target - Shen Fang -> had dinner with the daughter of the bank president at noon Intelligence Officer 3 surveillance: Target - Shen Fang -> had dinner with the daughter of the bank president at noon Intelligence Officer 1 surveillance: The target - Shen Fang -> went to the Gate of Joy for drinking in the evening, but did not return all nightCopy the code

After shen Lin understood the situation, he said, “Dear brothers, you don’t need to be stared at by everyone. You can take shifts and the others can have a rest and relax. Hence, elder brother several discussed, 1 first withdraw

Info.removeobserver (P1) info.setState(' go to the server ')Copy the code

The console prints:

Intelligence officer 2 monitored the situation: the target - Shen Fang -> had lunch with the daughter of the bank president at noonCopy the code

Publish and subscribe model

The publish-subscribe pattern is where an object wants to subscribe to a topic event based on a topic, so the publisher publishes a topic event based on a subscribed topic to inform each subscribed object to receive a message.

The publish-subscribe model is really different from the observe model. The difference is that the publish-subscribe mode has one more dispatch center than the observer mode. All publish topic events and subscribe topic events are done through the dispatch center.

Let’s look at the example above again. After switching to the publishing subscriber model, there is an additional dispatch center. Think of the intelligence center as the dispatch center.

Intelligence officers received orders from Shen Lin to monitor Shen Fang and began to monitor Shen Fang 24 hours a day.

Class Event {constructor(){this.listners = {} // All commands received by intelligence personnel} // subscribe method, Subscribe (type, fn){subscribe(type, fn){subscribe(type, fn){subscribe(type, fn){ Since multiple subscribers can subscribe to the event // Both Shen Lin and the director of the Central Bureau of Statistics issued orders to the information center to monitor Shen Fang. This.listners [type]) {this.listners[type] = []} // Put the subscribed callback method into the array this.listners[type].push(fn) // Unsubscribe events (unsubscribe monitoring) Return (type, fn) => {// If (! Type) {return false} // If fn under a subscribed event is not passed, cancel the whole subject event if(! Fn) {delete this.listners[type]} This.listners = this.listners[type]. Filter (item => item! == fn)}} publish(type,... Args) {let self = this // If you have not subscribed to this topic event at the time of publishing, you will not publish // Shen Lin asked the intelligence personnel whether there are any suspicious persons in the Gate of Joy recently, the intelligence personnel replied that they had not received this order, and could not give a reply. this.listners[type]) { return false } this.listners[type].forEach(item => { item.apply(self, args) }) } }Copy the code

We instantiate an object

let event = new Event()
Copy the code

Shen Lin issued the command to monitor Shen Fang

Subscribe (' Monitor Shen Fangs ', (content) => {console.log(content)})Copy the code

The director of the bureau issued the command to monitor Shen Fang

Subscribe (' command issued by the director of the Central Bureau of Statistics: monitoring the release of ', (content) => {console.log(content)})Copy the code

Release thematic events (Intelligence personnel report to Shen Lin)

Publish (' Shen Lin issued the command: monitor Shen Fang ', 'Report director, Shen Lin did nothing unusual today, as before; However, Director Ye also gave us the same order as you, which is to monitor silence.Copy the code

Release thematic events (Intelligence personnel report to Director Ye)

Publish (' order issued by the director of the Central Bureau of Statistics: monitor Shen Fang ', 'report to the director, Shen Lin as before, no abnormal behavior, is to go to work, to xishimen drink, go home ')Copy the code

Shen Lin hung up the phone, suspicious: director clearly know I am monitoring Shen Fang, why also deliberately issued an order again? And let them spy on other people? In order to verify his idea, Shen Lin decided to beat around the bush to find out, so he called the intelligence personnel: Is there any suspicious people in the Gate of Joy today?

The intelligence officer replied: Well… Chief, we didn’t receive your order to monitor the Gate of Joy. We were all focused on Shen Fang.

Event.publish (' what happened to the Gate of Joy ') // false Can't get a reply because no command was issuedCopy the code

After, the monitoring of Shen Fang was shen Fang found out, shen Fang in order to remove this let oneself eat and sleep hard monitoring, will embellish the matter told the military unification department director luo, luo director after listening to a rage, ask the meaning of several. Under this kind of pressure, the central plan to cancel the monitoring of Shen Fang.

Let unsubscribe1 = event. Subscribe (' subscribe ' Log (content) => {console.log(content)}) let unsubscribe = event. Subscribe Monitor Shen ', (content) => {console.log(content)}) // The intelligence personnel give up monitoring Shen ', (content) => {console.log(content)}) Publish (' publish ') event.publish(' publish ') event.publish(' publish ') event.publish(' publish ') event.publish(' publish ') Monitor Shen Fang ', 'report chief, Shen Lin as before, no abnormal behavior, just go to work, go to Joy gate to drink, go home ') // false Surveillance order liftedCopy the code