Publish / subscribe model

There are a lot of people mentioned publication, subscription model big head, do not understand people will think he is doing ah observer mode and what difference does it

In fact, the difference between publish and subscribe model observer pattern is still very large, subscription model release one more than the observer mode scheduling part

Although there are two modes of subscribers and publishers (specifically observers considered to be a subscriber, specific goals can be considered a publisher), but by the specific objective observer pattern is scheduled, and publish / subscribe model is unified by the scheduler Center tone, it is dependent on the presence of the observer pattern between the subscriber and the publisher, and publish / subscribe model does not.
In the publish-subscribe model, components are loosely coupled, and just opposite the observer mode.
When it comes to publish subscription model, because the relationship is one to one or one to many, in fact, the realization that you want to publish something to keep an object or an array of them, with a direct call to traverse
code show as below:
PubSub function () { 
  var Topics = {}; 
  function SUBSCRIBE (Topic, Fn) { 
    IF {(Topics [Topic]!) 
      Topics [Topic] = []; 
    } 
    // No de-emphasis, if it can not be used to weight destructuring assignment, since the [... new Set (arr)] In this manner only to the basic weight value type, fn is a function of a reference type 
    Topics [Topic] .push (Fn); 
  } 
  function publish (Topic, args ... ) { 
    // the console.log (Topics [topic] .length) 
    IF (Topics [topic] return);! 
    // iteration values corresponding to the same topic function 
    for (Fn of the let Topics [topic]) { 
      Fn (... args) 
    } 

  } 
  return { 
    SUBSCRIBE, publish 
  } 
} 
var pubSub1 new new PubSub = (); 
pubSub1.subScribe ( 'the Add', function (A, B) { 
  the console.log (A + B) 
})
pubSub1.subScribe('minus', function (a, b) {
  console.log(a - b)
})

 

看完这个是不是感觉发布订阅模式很简单呢

Guess you like

Origin www.cnblogs.com/wb336035888/p/12530234.html