Observer is a behavioral design pattern. It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state.
The observer pattern is also known as Dependents or Publish-Subscribe.
It describes the coupling between the objects and the observer.
It provides the support for broadcast-type communication.
It defines a one-to-many relationship between objects.
It is very useful when the framework we writes and needs to be enhanced in future with new observers with minimal changes.
How Observer Pattern works
The observer pattern works by using two main components: the subject and the observer.
The subject is an object that has some state and some behavior.
The subject can register and unregister observers and can notify them about any changes in its state.
The observer is an object that implements a common interface, which defines a method to update itself when the subject changes.
The observer can register itself with the subject and can unregister itself when it is no longer interested in the subject's state.
The subject and the observer can communicate through the common interface, without knowing the details of each other's classes.
How observer Pattern works
How observer Pattern works
Benefits of Observer Pattern
The subject and the observers can be reused in different contexts, if they implement the common interface.
The subject does not need to know the details of the observers, and the observers do not need to know the details of the subject.
The subject and the observers can be added, removed, or changed at runtime, without affecting the rest of the system.
The subject can notify any number of observers, and the observers can react to the subject's changes in different ways.
The subject and the observers can run in different threads or processes and communicate through events.
The observers can process the events in parallel, without blocking the subject. This allows for the subject and the observers to adapt to changing requirements and scenarios.
Disadvantage of Observer Design pattern
The subject and the observers must maintain a consistent and coherent state and synchronize their updates.
They must also manage the registration and unregistration of the observers and handle any errors or exceptions that may occur.
Additionally, the subject and the observers must handle the memory management and the lifecycle of the objects and avoid memory leaks.
This pattern can also cause performance issues, as the subject and the observers may consume more resources than necessary.
Furthermore, it can create hidden dependencies and side effects, as the subject and the observers may depend on each other implicitly and affect each other's behavior.
Comments