Observer Design pattern
Just Imagine we are working in a monitoring-based company. we have a monitoring tool that receives data from various external devices.
Requirement
For that received data from various devices, we need to create different views and users should have the flexibility to add and remove the views at any point in time. Initially, we have three views.
- Metric Processing
- Synthetic Monitoring
- Alert Processing
Initial Design
Initially, we come up with the below-mentioned design
Let's Analyze the drawbacks of our Initial Design:
To Add or Remove any View (For add or Remove the concrete classes of the create view Interface) we need to Touch the Metric Data class. It will create two problems.
- There is a tight coupling between the Views and Metric Data classes. Let's Imagine In the future User will create 1000 views, it is very difficult to maintain the code
- what if we need to add the views during Runtime, This looks hard coded.
Final Design
To overcome the above problems, we brainstorm and will decide to Implement the Observer Design Pattern.
Observer Design Pattern
The observer design pattern works like the publisher + subscribers model.
For Example, if you take a subscription to our blog, if any new posts are published, you will be notified, if you unsubscribe, you will not be notified. Similarly, the Observer pattern works.
Here we are notified as Subject (Blog writer) and you will be notified as Observer (Subscriber).
Let's discuss how we apply this Observer design pattern for our monitoring application.
Metric Data is the Subject, views are the Observers
we can add and remove the Observer at any point in time.
In the above design, we observed below points
Oops Basics covered in this design
- Inheritance
public class MetricProcessing implements View, Observer {
}
Abstraction And Encapsulation
private static List<Observer> observers = new ArrayList<>();
Oops principles covered in this design
- Encapsulate what varies
In this pattern state of the subject and the number of observers always change, we can vary the number of observers without changing the Subject. In this application, every time we are receiving new metric data and we can capable to create a more number of views without changing the Metric Data
- Favorable Composition Over inheritance
we can capable to compose any number of observers, they can be set up even at runtime
- Program to interfaces, not for Implementations
In this pattern, the Subject is the Interface and Observer is the Interface. The subject can keep track of all Observers by adding, removing and notifying
Observer design pattern defines a one-to-many relationship dependency between objects, If the state changes in Subject, it notified to all its dependents and they are loosely coupled
CODE FOR COMPLETE IMPLEMENTATION: