Observer vs Publisher-Subscriber Pattern
Observer Design Pattern:
"An Observer Pattern says that "just define a one-to-one dependency so that when one object changes state, all its dependants are notified and updated automatically".
The observers are dependent on the subject such that when the subject’s state changes, the observers get notified.
1.) When you subscribe to any website.
You are on observer in this case who has subscribed to a website (Subject) for getting notified about its post.
2.) Cricket Display
The scoreboard display, displays the average score etc information as per the current status of the match. Whenever any score changes, the scoreboard gets refreshed. So, display board is the observer here and Subject is the panel sending the current score status to the board.
3.) Whatsapp Group
Whenever any person sends any message in the group, all the people who are in the group get notified.
Pub-Sub Design Pattern:
" In ' Publisher Subscriber ' pattern , sender of message is called subject and receiver is called object. In this patter sender do not send message directly to the receiver."
In this example publisher and subscriber do not know about each other .If publisher want to send the message to subscriber then he can send the message through third component called event bus. which is known by both publisher and subscriber, which filters all incoming messages and distributes them accordingly.
Difference between Observer and Pub-Sub pattern:
- In the Observer pattern, the observers are aware of the observable. But, in Pub-Sub pattern, publishers and subscribers don’t need to know each other. They simply communicate with the help third component.
- In Pub-Sub pattern components are loosely coupled. But in Observer pattern components are tightly coupled.
- Observer pattern is mostly implemented in a synchronous way, i.e. the observable calls the appropriate method of all its observers when some event occurs. The Pub-Sub pattern is mostly implemented in an asynchronous way (using message queue).
- Observer pattern are implemented in single application address where as pub-sub pattern are implemented in cross application.