This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging
Publish the definition of the subscribe pattern
When we look at books on design patterns, we will find that when they introduce the observer pattern and the publish/subscribe pattern, they mix the two patterns together (either under the name observer or publish/subscribe). In fact, the publis-subscribe pattern is one of the most commonly used implementations of the observer pattern and is superior to the typical observer pattern from a decoupling and reuse point of view. In conclusion, the publish/subscribe pattern is a variation of the observer pattern, but it is essentially the observer pattern.
I’ve singled it out here because there are some differences between the publis-subscribe model and the traditional observer model. Compared with the observer mode, the publish/subscribe mode has more event channels. The event channel serves as the scheduling center to manage the subscription and publication of events, and completely isolates the dependency between subscription and publication. That is, when subscribing to events, one does not care who publishes them. When publishing an event, you don’t care who subscribing; In both cases, only the event itself is concerned.
If the observer pattern is programmed for target objects and observers, the publish/subscribe pattern is programmed for dispatch centers. The former coupling the target object and the observer; The latter decouples publishing and subscription and is managed by a scheduling center.
Application scenarios of the publish/subscribe pattern
For real developers, the publish-subscribe model applies to the following scenarios:
- Widely used in asynchronous programming, it is an alternative to passing callback functions
- Subscribe to error and SUCCESS events for Ajax requests
- Binding and firing of event functions on DOM nodes
- If you want to do something after each frame of the animation, you can subscribe to an event and post the event after each frame of the animation is completed
Pros and cons of the publish-subscribe model
Advantages:
- Flexible, publish and subscribe are decoupled and do not affect each other as long as the event channel of publish and subscribe pattern is introduced as the scheduling center
- Scalability, each time to add or reduce, directly call the method provided by the scheduling center on the line
Disadvantages:
- Flexibility is both a strength and a weakness, and when not used properly it can lead to messy data flows (i.e. publish and subscribe incorrectly), resulting in code that is not easy to maintain
- Performance costs are higher. The publisit-subscribe pattern requires maintaining a separate event queue, and the more events subscribed to, the greater the memory consumption
Analysis of the implementation principle of publish – subscribe pattern
Let’s analyze the implementation steps of the observer pattern:
- Create an EventCenter as the scheduling center
- Implement methods to subscribe to events (Listen) and publish notifications (trigger) in the event channel
- Event channels are instantiated, subscribed to, and published through event channels
Concrete implementation code
Write the code along the lines of the previous step
// The event channel acts as the dispatch center
var EventCenter = function(){
this.eventCache = {};
};
// Subscribe to events
EventCenter.prototype.listen = function(type, fn) {
if(!this.eventCache[type]) {
this.eventCache[type] = [];
}
this.eventCache[type].push(fn);
}
// Publish the event
EventCenter.prototype.trigger = function(type, msg) {
if(!this.eventCache[type]) return false;
var fns = this.eventCache[type];
var count = fns.length || 0;
while(count--) {
varfn = fns[count]; fn(msg); }}// Instantiate the event channel
var event = new EventCenter();
// Subscribe to listen
event.listen('click'.function(msg) {
// Logic executed at release time
console.log('listen:', msg);
});
// Release notification
event.trigger('click'.'Content of notice Issued');
// The final console output:
// Listen: indicates the content of the notice
Copy the code