Observer model

Description:

The Observer Pattern consists of the observed and the Observer. The Observer can be multiple. The observed maintains multiple observers, such as adding or deleting observers. When data changes are observed, each observer maintained is notified by broadcast (that is, by calling the observer supplied callback function).

Summary:

Observer pattern: Defines a one-to-many dependency between objects in which all dependent object Observers are notified when the state of the target object Subject changes

Here’s an example:

Mei has attracted two suitors through her own efforts. Every time Mei posts on wechat, she invariably gets two responses from her suitors. Mei’s relationship with the two suitors forms the observer model. Mei is the observed, and the two licking dogs are the observers. This action will trigger a dog licking response

Class ABeautifulGirl {TIAN_GOU_LIST = [] // Add observer to attractTianGou(... tianGous) { Array.prototype.push.apply(this.TIAN_GOU_LIST, KickOffTianGou (tianGou) {const index = this.tian_gou_list.indexof (tianGou) this.TIAN_GOU_LIST.splice(index, } // sendPost(data) {this.tian_gou_list. forEach(tianGou => {tiangou.callback. call(tianGou, })}} constructor(constructor(name, constructor) {this.name = name this.lick = fn} callback(data) {console.log(' I am ${this.name}. Const tiangou1 = new TianGou('tiangou1',) this.lick()}} // Define two observers }) const tiangou2 = new TianGou('tiangou2', Const xiaomei = new ABeautifulGirl() => {console.log(' Please drink more hot water ')}) Xiaomei. AttractTianGou (Tiangou1, Tiangou2) // The little beauty got a friend circle xiaomei. SendPost (' Tummy ache ')Copy the code

Here’s another chestnut

Lick the dog licked several times from beginning to end to the favor of small beauty, this time he learned to take the initiative, he is ready to hook up with a goddess, so he thought of ways to add small Beauty’s micro letter, began to observe two people at the same time.

class ABeautifulGirl { constructor(name) { this.name = name } TIAN_GOU_LIST = [] sendPost(data) { Console. log(' ${this.name}, send a friend ') this.tian_gou_list. forEach(tianGou => {tiangou.callback. call(tianGou, Data)})}} Class TianGou {constructor(name, constructor) fn) { this.name = name this.lick = fn } subscribe(publish) { var sub = this var alreadyExists = Publish.tian_gou_list. some(function (item) {return item === sub}) // If (! alreadyExists) publish.TIAN_GOU_LIST.push(sub) return this } unsubscribe(publish) { var sub = this publish.TIAN_GOU_LIST  = publish.TIAN_GOU_LIST.filter(function (item) { return item ! == sub}) return this} callback(data) {console.log(' ${this.name} ') // Const xiaomei = new ABeautifulGirl('xiaomei') const xiaoli = new ABeautifulGirl('xiaoli') Const tiangou1 = new TianGou('tiangou1', }) const tiangou2 = new TianGou('tiangou2', () => {console.log(' Please drink more hot water! ')}) // Subscribe (xiaomei) Tiangou2. subscribe(xiaomei) // Xiaomei. sendPost(' tummy pain ') xiaoli.sendPost(' waist pain ')Copy the code

The advantages and disadvantages:

The advantages are obvious: reduced coupling, and both focus on their own functions; The disadvantages are also obvious: all observers are notified and there is no filtering;

Publish and subscribe model

Publisher && Subscriber

Description:

Licking dogs subscribed to many goddesses, but most of them failed. Among licking dogs, there was a smart dog, let’s call it Erha. Erha first realized that it was useless for the goddesses to just drink more hot water when they were sick. Go to the infusion to talk about losing miss you night to the goddess. Erha started to act, so Erha learned the publish and subscribe model.

Summary:

Publish and subscribe mode: Based on an event (topic) channel, the object Subscriber that wants to receive notification subscribes to the topic through user-defined events, and the object Publisher that is activated notifies each Subscriber that subscribes to the topic by publishing the topic event. The publishable/subscriptive model differs from the observer model in that a “third party” (event center) emerges. The target object does not notify the observer directly, but rather sends notifications through the event center.

Here’s an example:

const GirlsHub = function () { this.grils = {} this.on = function (name, cb) { if (this.grils[name]) { this.grils[name].push(cb) } else { this.grils[name] = [cb] } } this.trigger = function (name, ... arg) { if (this.grils[name]) { this.grils[name].forEach(eventListener => { eventListener(... Arg)})}} let girls = new GirlsHub() girls.on('morring', () => {console.log(' morring')}) girls.on('morring', () = > {the console. The log (' said "good morning" to xiao li ')}) girls) on (' morring, () = > {the console. The log (' said "good morning" to small beautiful ')}) girls. On (" noon ", () = > {the console. The log (' said to the little beauty good afternoon ')}) girls) on (" noon ", () = > {the console. The log (' say to the small beautiful afternoon ')}) girls. On (" noon ", () = > {the console. The log (' said to the little beautiful afternoon ')}) girls) on (' evening, () = > {the console. The log (' said to the little beauty good night ')}) girls. On (' the evening, () = > {the console. The log (' for small beautiful said good night ')}) girls. On (' the evening, () => {console.log(' say good night ')}) girls.trigger('morring') girls.trigger('noon') girls.trigger('evening')Copy the code

After learning, two ha passive for active, every time to the goddess began to send a message, this thought can harvest the goddess of the heart, to later found that he was screened by half of the people.

I guess I didn’t have enough skills. The following additional design patterns need to be learned to optimize the following solutions.

The advantages and disadvantages:

Advantages: Better decoupling, fine granularity is easier to control;

Disadvantages: hard to read, extra object creation, time and memory consumption

The correlation and difference between the two modes

The publish-subscribe model is more flexible and is an advanced version of the observer model, specifying distribution.

  1. The observer mode maintains the relationship between a single event and multiple objects that depend on the event.
  2. Publish-subscribe maintains relationships between events (topics) and objects that depend on each event (topic);
  3. In observer mode, the target object triggers notifications directly (all notifications) and the observed object is forced to receive notifications. Publish subscribe mode has an intermediate layer (event center), which manages the notification broadcast (only notifies the objects that subscribe to corresponding events);
  4. There is a strong dependency between objects in the observer mode and real decoupling between objects in the publish-subscribe mode.