DEV Community

Discussion on: The Observer Pattern: A Solution for Subscription-Reliant Applications

Collapse
 
jasaaan profile image
Jason Lim

Thanks for the great write up! Found it extremely easy to follow, and I like how your post helped me understand with very relatable real life examples, plus the addition of UML diagrams (instead of just a chunks of codes) to aid my understanding. It'd be nice to know more about the pros & cons so I know what to look out for when implementing the pattern in future!

You mentioned that one of the reasons for using the Observer pattern is that it makes the app more reactive - instead of leaving the app in a blocked state or constantly polling. I also wanted to add on another benefit which is the fact that it follows the open-closed principle (a class should be open for extensions without having to change the class). In the Observer pattern, we can add as many observers as we want without having to change the code. I have also played around with some libraries supporting the Observer pattern e.g. react-intersection-observer and the Observer pattern is indeed widely used in UI rendering and responding to certain events.

Also, I used to be really confused between the Publisher-Subscriber pattern (pub-sub) and the Observer pattern. I always thought they were the same thing. Here is a quick summary that might help anyone also confused between the two:

In the Observer pattern, all Observers are aware of the Subject and the Subject also keeps a list of Observers. The Subject notifies all Observers in response to certain events.
In a Publisher-Subscriber pattern, similarly, the Subject (Publisher) notifies the Observers (Subscribers). However, there is a component in-between called a message broker which is known by both the publisher and subscriber - its job is to filter the messages and dispatch them accordingly.
They both look quite similar at first glance. The key difference would be that in a pub-sub pattern, the publisher and subscribers are not aware about the existence of each other whereas in the Observer pattern, the Subject has a list of Observers at hand. Hence, the pub-sub pattern is also loosely coupled.

Thanks again for the informative post! Was also nice to hear about your experience with the Observer pattern during your internship - proving it's useful and still widely used!