top of page

Observer vs Pub/Sub Pattern

Updated: Jan 28, 2023

Observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods - Wikipedia definition


Lets explain it in layman's terms.


Let's assume you are a student and registered with some institute for getting training. Whenever a new batch started, institute is giving notification to all the students about the new batch.

Here, Institute is the subject, and student is an observer, institute maintains. a list of observers(students).


Publisher-Subscriber Design Pattern

publisher-subscriber Design Pattern is conceptually similar to the observer design pattern.


In the publisher-subscriber pattern, senders of messages, called publishers, do not program the messages to be sent directly to specific recipients, called subscribers.


This means that the publisher and subscriber don't know about the existence of one another.


There is a third component, called broker, message broker or event channel, which is known by both the publisher and subscriber. It filters all incoming messages and distributes them accordingly.


Publisher-Subscriber is a pattern used to communicate message between different system components, without these components knowing anything about each other's identity.


So, in a nutshell, the major difference between these two patterns can be shown like this:


Let's list the differences in a summary:

In the observer pattern, the observers are aware of the subject. The subject maintains a record of each observer.

publishers and subscribers don't need to know each other. They simply communicate with the help of message queue or a broker.

Tightly coupled.

publisher-subscriber pattern components are loosely coupled.

The observer pattern is mostly implemented synchronously, i.e., the subject calls the appropriate method of all its observers when an event occurs.

The publisher-subscriber pattern is mostly implemented asynchronously (using a message queue).

The observer pattern needs to be implemented in a single application address space.

publisher-subscriber pattern is more of a cross-application pattern.

 

Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark



bottom of page