Publish/Subscribe Protocol is a model to control the event flows (changes of data) in software using two entities: subscriber and publisher. The event is used to signal changes from publisher to subscriber(s). From here, we can conclude the publisher is the producer of events, and the subscriber(s) is the consumer of the events that it needs.
The publisher doesn’t need to have any explicit knowledge of the subscriber, plus the subscriber(s) can have its own agenda different from others. That being said, the publisher should keep track of who is subscribing to it, and call each of them in turn and notify them if an event occurred. In case where the subscriber(s) decides to unsubscribe from the publisher (it doesn’t need that information any more), it should remove that subscriber from subscribers list in order to prevent it from getting notified.
Note: Avoid having a subscriber that has to handle more than enough or all the events that they don’t need. It will decrease the coupling since it doesn’t have the knowledge# about them in order to interact with so many objects.
There are many implementations of Publish/Subscribe Protocol:
- peer-to-peer
- centralisation (software bus like CORBA Event Service#, an object responsible to maintain a database of listeners and distribute the messages accordingly), and
- broadcast (regardless of registration).
We can further #decouple the model using Model-View-Controller (MVC)#.
However, there could be two extreme cases by adopting this protocol: push model and pull model. Push model happen when the publisher sends subscribers detailed information about the change without determining whether it is necessary. This might make the subscribers less reusable. Pull model is on the opposite polar where the observer ask details after the minimal notification from publisher. It is rather inefficient. These two model could be avoided if a parameter of the interests that the subscriber needed is passed during an update. That way, only needed details are passed to the observer.