When someone follows you on Instagram, you get a notification. When someone likes your post, you get a notification. When someone comments on your post, you get a notification. What’s one common action between these events? That's right, you get notified about something that you might be interested in knowing. Think about this for a few seconds, how common is it? And have you ever wondered how it’s implemented?
Introduction
If you’re developing interactive software, you’re bound to come to a point where you need to notify your users about some actions (whether they are passive or active notifications). This situation is so common that, of course, a design pattern has been formed. The Observer is a software design pattern where an object notifies its observers (subscribers) automatically for specific events.
How does it work?
It defines a one-to-many dependency between objects so that when one object changes state, all of its dependencies are notified and updated automatically. Objects can even decide at runtime whether they want to be informed or not.
What problems does it solve?
This pattern was created in order to solve 2 problems: observers wasting time checking the subject for the necessary data or the subject wasting resources notifying the wrong observers.
How do we solve this problem?
Whenever an important event happens to the subject, it goes over its observers and calls the specific notification method on their objects.
The pattern suggests that you add a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher. This mechanism consists of the following:
- A data structure (most commonly an array) for storing a list of references to subscribed objects
- Multiple public methods which allow adding subscribers to and removing them from that list
“Real apps might have dozens of different observer classes that are interested in tracking events of the same subject class. You wouldn’t want to couple the subject to all those classes. That’s why it’s crucial that all observers implement the same interface and that the publisher communicates with them only via that interface. This interface should declare the notification method along with a set of parameters that the subject can use to pass some contextual data along with the notification.”
Design principles taken into account:
- Loose coupling between objects
- Encapsulate what varies
- Composition over inheritance
- Program to interfaces, not implementations
Literature
If you want to learn more I highly recommend the book: Head First Design Patterns. It's an amazing and very understandable approach to explaining patterns and design principles.
I also recommend the following website: refactoring-guru and make sure to check out this very good YouTube video explaining the Observer pattern in practice.
Thank you for your time ❤️. If you have any questions or suggestions, leave a comment down below.