Publish/Subscribe Pattern

A publish/subscriber pattern (in short pub-sub) is sometimes also referred to as Event Aggregation. In this pattern, different components of the application communicate with a topic/event channel.

When using this pattern, the components of the application are loosely coupled. Unlike observer pattern where all the observers depend on the notifications from a subject, in the pub-sub pattern the components rely on an event channel. 

In other words, in the observer pattern, the observers subscribe to the object firing the events (the subject). But in the pub-sub, the event channel sits between the notifier (publisher) and the subscriber.

Publish/Subscribe Implementation

To implement a pub-sub module, we need following components:

  • An object to keep track of
    1. the topic or the event
    2. the subscribes to be associated with this topic/event.
  • A subscribe method to associate a subscriber with a topic/event.
  • An unsubscribe method to dissociate a subscriber form a topic/event.
  • A publish method to publish/trigger/emit a topic with optional data.

Here is the code for a pub-sub module with the explanation added as comments.