PubSub Vs Observer Pattern

Both PubSub and the Observer Pattern allow a central source to send out messages (these could include data, event notifications etc) that then cause/allow various other objects to update or change. There is a simple but subtle difference, however.

In the observer pattern, the publisher (subject/observable) has knowledge of the subscribers (observers). In the PubSub pattern, any service that needs the information being published can willingly subscribe to that publisher. The publisher has no knowledge of the specific subscribers, but simply publishes the message to a channel. Depending on the implementation, it does not need to be a public channel. Amazon SNS, for example, allows you to restrict the subscribers to specific servers or networks.

You can think of PubSub as being akin to a broadcast model. Think of a radio station “publishing” its content on the airwaves, with no knowledge of who will tune in. The “subscribers” are those who have chosen to tune their radio to that station.

The observer pattern is more akin to a home delivery newspaper. The publishing company must know the name and address of every subscriber ahead of time to deliver their content.

Both have advantages and disadvantages. For example, in the PubSub model your publisher is allowed to be a much more abstract service. It does not need any specific (concrete) knowledge of the other services or objects in a system. All it needs is to know how to publish its message when it is time. Everything else is left up to the other services.

The observer pattern allows more centralized control. While the subject (publisher) needs to have intimate knowledge of all observers, it also has control over who receives its messages. It can centrally decide to stop publishing updates to specific observers, or it can choose to add an observer.

PubSub Vs Observer Pattern

Leave a Reply

Your email address will not be published.