1.Observer mode requires that an observer who wishes to receive a topic notification must subscribe to an event that changes the content.
The 2.subscribe/publish mode uses a theme/event channel between subscribers and publishers. The event system allows code to define specific events for an application that can pass custom parameters that contain the values required by the Subscriber. The goal is to avoid dependencies between subscribers and publishers.
Unlike the observer mode, it allows any subscriber to execute an appropriate event handler to register and receive notifications from the publisher.
Okay, I don't know. Here's what I understand:
1. In the observer model, the target object is responsible for maintaining the observer. In the Publish/Subscribe mode The Publisher does not care about the subscriber and is only responsible for throwing the message out.
2. In the Observer model, the Observer provides an interface and then calls this interface when the target object changes to keep its state and target State consistent. That is, all observers should have a unified interface (such as the Update method written above, everyone's method should be called this name). In the Publish/subscribe mode, the trigger for the Subscriber event is not to rely on such an interface, but rather to trigger the subscriber by listening for a particular message that typically contains the name and the parameters required by the Subscriber. It is understandable that the subscriber listens not to the publisher, but to the message pool, as long as it has a message in its care, that is, to trigger the event, regardless of who posted the past. The publisher and Subscriber are decoupled.
The following is the implementation of the Publish/subscribe mode in JS, copy and paste to the console inside try to understand:
var pubsub = (function () {
var q = {}
topics = {},
subuid =-1;
//Post message
Q.publish = function (topic, args) {
if (!topics[topic]) {return;}
var subs = Topics[topic],
len = subs.length;
while (len--) {
subs[len].func (topic, args);
}
return to this;
};
//Subscribe event
q.subscribe = function (topic, func) {
Topics[topic] = topics[topic]? Topics[topic]: [];
var token = (++subuid). toString ();
Topics[topic].push ({
Token:token,
Func:func
});
return token;
};
return q;
//unsubscribe will not be written, traverse topics, then return token by saving before deleting the specified element
})();
//triggered event
var logmsg = function (topics, data) {
Console.log ("Logging:" + topics + ":" + data);
}
//Listening to the specified message ' Msgname '
var sub = pubsub.subscribe (' Msgname ', logmsg);
//Post message ' Msgname '
Pubsub.publish (' msgname ', ' Hello World ');
//Post unattended message ' msgName1 '
pubsub.publish (' Anothermsgname ', ' Me too! ');