20 July 2020
What is the difference between Observer Pattern and Pub-Sub
Observer Pattern
The 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.
When the observed object, the Subject, has a state change it will call the Observers directly. There might be multiple observers for each subject. There is no assumption about the notification mechanism however it’s typically just a direct function call. The observer pattern is mostly implemented in a synchronous way i.e. the observers are notified immediately when some event occurs.
The observer is very common in Javascript and Java. Especially to implement event driven applications. For example, you can define a button in HTML DOM and have a set of functions listen to the button click event.
<button id="myBtn"/>
document.getElementById("myBtn").addEventListener("click", function() {
console.log("myBtn has been clicked! Time to do something")
});
Pub-Sub (Publisher-Subscriber) Design Pattern
At first glance Pubsub sounds the same to the Observer. In fact, many design pattern books or articles use the ‘Publisher-Subscriber’ notion to explain Observer pattern. However there is a major difference between Pub-Sub and Observer and that is
In ‘Publisher-Subscriber’ pattern, senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers.
This means that the publisher and subscriber don’t know about the existence of each other. There is a third component typically called broker, messenger, or event bus which knows both the publisher and subscriber. This broker will handle, deliver, filter, prioritize and sometimes even store the messages. The pubsub pattern is mostly implemented in an asynchronous way using message queues.
The PubSub pattern is very versatile and over the years we have seen multiple commercial products implementing it typically under the name message queue. Some examples are RabbitMQ, Redis, Kafka, etc. You can even see the genetics of this pattern in Flux and React Redux.
Conclusion
Now that it’s clear what Observer pattern and Pub-Sub pattern does, I hope that this guide will be helpful for some body. Thanks for reading and see you in the next post.