Observer mode and subscription/publisher mode

Source: Internet
Author: User

While looking at the data, someone has equated the observer (Observer) pattern with the Publish (Publish)/subscribe (Subscribe) pattern, and some people think that the two patterns are still different, and I think there is a difference, essentially the difference is the place of dispatch.

Observer pattern

The interpretation of the comparison concept is that the target and the observer are the base class, the target provides a series of methods to maintain the observer, and the Observer provides an update interface. Specific observers and targets inherit their own base classes, and then the specific observer registers themselves with the specific target, scheduling the Observer's Update method when the specific target is changed.

For example, there is a "weather center" specific target A, specifically monitoring the weather changes, and a display of the weather interface of the Observer b,b himself registered to a, when a triggered the weather changes, dispatch B's Update method, and bring their own context.

Publish/Subscribe Mode

The explanation of the comparison concept is that the subscriber registers the event that he wants to subscribe to the dispatch center, when the event triggers, the Publisher publishes the event to the Dispatch center (incidentally), and the dispatch center uniformly dispatches the subscriber to the dispatch center's processing code.

For example, an interface is a real-time display of weather, it subscribes to weather events (registered to the dispatch center, including handlers), when the weather changes (timing to obtain data), as the publisher to publish the weather information to the dispatch center, dispatch center scheduling subscribers ' weather handlers.

Summarize

1. From the two pictures can be seen, the biggest difference is the place of dispatch.

Although both modes have subscribers and publishers (the specific observer can be considered subscribers, the target can be considered as publishers), the Observer pattern is scheduled by the target, and the Publish/subscribe pattern is unified by the dispatch center, so there is a dependency between the Subscriber and the publisher of the Observer pattern, and the release/ The subscription mode does not.

2. Two modes can be used for loose coupling, improved code management and potential reuse.

Appendix

Observer Pattern Implementation code (JavaScript version):

Observer list function observerlist () {this.observerlist = [];} ObserverList.prototype.add = function (obj) {return this.observerList.push (obj);};o BserverList.prototype.count = function () {return this.observerlist.length;};o BserverList.prototype.get = function (index) {if (Index >-1 && Index < this.observerList.length) {RET  Urn this.observerlist[index];  }};observerlist.prototype.indexof = function (obj, startIndex) {var i = StartIndex;    while (I < this.observerList.length) {if (this.observerlist[i] = = = obj) {return i;  } i++; } Return-1;};o BserverList.prototype.removeAt = function (index) {this.observerList.splice (index, 1);};/ /target function Subject () {this.observers = new observerlist ();} Subject.prototype.addObserver = function (Observer) {THIS.OBSERVERS.ADD (Observer);}; Subject.prototype.removeObserver = function (Observer) {THIS.OBSERVERS.REMOVEAT (THIS.OBSERVERS.INDEXOF (Observer, 0) );}; Subject.prototype.notify = function (ContexT) {var observercount = This.observers.count ();  for (var i=0; i < Observercount; i++) {This.observers.get (i). Update (context); }};//Observer function Observer () {this.update = function () {//...};}

Publish/Subscribe Pattern Implementation code (JavaScript Classic):

var pubsub = {};(function (myObject) {//Storage for topics, can is broadcast//or listened to var topics =    {};    An topic identifier var subuid =-1; Publish or broadcast events of interest//with a specific topic name and arguments//such as the data to pass a        Long myobject.publish = function (topic, args) {if (!topics[topic]) {return false; } var subscribers = Topics[topic], len = subscribers?        subscribers.length:0;        while (len--) {subscribers[len].func (topic, args);    } return this;    }; Subscribe to events of interest//with a specific topic name and A/callback function, to be executed//WH En the topic/event is observed myobject.subscribe = function (topic, func) {if (!topics[topic]) {T        Opics[topic] = [];        } var token = (++subuid). toString ();            Topics[topic].push ({token:token,Func:func});    return token;    }; Unsubscribe from a specific//topic, based in a tokenized reference//to the subscription MYOBJECT.UNSUBSCRI is = function (token) {for (var m in topics) {if (Topics[m]) {for (var i = 0, J = Topics[m].length; I < J;                        i++) {if (Topics[m][i].token = = = token) {Topics[m].splice (I, 1);                    return token;    }}}} return this; };} (PubSub));

Reference documents

1. "Learning JavaScript Design Patterns" by Addy Osmani

This article for the original article, reproduced please retain the original source, convenient traceability, if there is the wrong place, thank you correct.

This address: http://www.cnblogs.com/lovesong/p/5272752.html

Observer mode and subscription/publisher mode (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.