And then maybe you’re going to go into a project that uses this model, and you’re going to learn, and you’re going to learn from the Internet.
1. first try
The first one I read was an article by the Nuggets, which gave me a preliminary understanding of the difference between the observation model and the publish and subscribe model.
-
Observer mode: An object is observed by many observers. When the object changes, notify all observers of the change. Like in MVC architecture, when the data changes, the view changes.
-
Pub/SUB mode: At first glance it looks very similar to the Observer mode, with one PUB and many subs, but the difference is that there is no direct communication between the two sides of the pub/ Sub mode. Pub does not notify sub. The connection between them is through the broker (plus a layer of uncertainty). When A PUB sends A message, for example to topic A of the broker, the broker filters the pub’s message and distributes it to subs, not necessarily to all subscribers, but only to subscribers to Topic A.
2. The illustration
As shown above. You can also use this demo to understand more.
- As you can see, in the pub-sub mode, one subscriber can subscribe to multiple topics, or multiple subscribers can subscribe to the same topic.
- In addition, you can see that subscribers are free to subscribe and unsubscribe.
3. Event monitoring
EventListener in JS is actually a PUB /sub mode.