Design Patterns Days: Observer Pattern and Publishing/Subscribing
Overview
As the wikipedia definition says:
The observer pattern is a software design pattern in which an object, named 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.
To someone not familiar with this pattern the first thing that would come to their mind is Polling. If we want to know about changes that are done to a central body/system we continuosly send request to the server and check for changes based on the responses But the problem with this approach is, with a significant increase in clients that are polling the system, the continuous request going to the system will overwhelm the system. Also making huge amount of IO/Network requests is bad (Just take my word for it).
Example Scenario
You have made a Earthquake detection system that sends notification to all the houses in the area, the notification being sent here can be sms/email but we are interested in how the client (Subscribers) will interact with the Earthquake Detection System (Publisher).
Code Example
Setting up Publishers and Subscriber Interfaces
|
|
The Central Earthquake Detection system, our publisher will implement three methods
- Add - To add the list of clients that want to listen to messages sent by the system
- Remove - Remove a particular subscriber from the list
- notifySubs - To send a particular message to all the clients
The Clients on the other hand will have to ovveride only the update method, ie what to do with the message recieved from the publisher.
|
|
Other PubSub Systems
Using the Observer Design Pattern is something which comes in handy if we want to implement PubSub between objects, in a more complex distributed system where The Producer and Consumer are seperate services pubsub tools like Kafka and other alternatives are used.