Observer Design Pattern
What is Observer Design Pattern:
Observer design pattern define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically -GoF.
Observer design pattern is a type of behavioral design pattern that creates a relationship between objects where one object is the subject and the other objects are observers. The subject maintains a list of its observers and informs them automatically whenever there is a change in its state.
The observer design pattern have two main concepts.
- Subject. They are the publishers. It notify all the observers when a change occurs to in its state.
- Observers. They are the subscribers. They simply listen to the changes of the subjects.
Example as a Youtube Channel:
Youtube channel offers subscribe option to be notified when a new videos are uploaded. When we subscribe the channel we got the notifications message. If there is no such options, youtube can send notification to all users or no one or randomly. In that case, some users will get unwanted notification that made them bad experience. Some users did not notify, they actually want it for that channel. As a result they have to visit the channel several time to be updated.
Video uploading and subscriber notification can be implemented using the Observer design pattern. Here is a high-level description of how it might work:
- A user uploads a video to the channel. This video is the “subject” in the Observer pattern.
- The system maintains a list of “observers” (subscribers) who are interested to be notified for new videos.
- When a video is uploaded, the system iterates through the list of subscribers and sends a notification to each one.
- Each subscriber receives the notification and can take appropriate action, such as watching the video or dismissing the notification.
Useful Situation for Observer Design Pattern:
- Event handling: When an event occurs, multiple objects need to be notified.
- Model-View-Controller: In MVC, the model represents the data, the view represents the presentation. The Observer pattern can be used to notify views of changes in the model and vice versa.
- Logging and Auditing: When an action takes place, multiple objects might want to know about it, such as a logger, an auditor or an emailer. The Observer pattern allows objects to register as observers and be notified when an action takes place, so they can perform their respective tasks.
Implementation of Observer Design Pattern (Fig-1):
In the above programming, I have created two channel objects(Music and Educational) and three users(Jhon, Mari and Jim). Jhon loves music so he subscribe the music channel. Mari and Jim are student. They have subscribe the Educational channel.
When video has been uploaded, as per subscription user will be notified. To implement this code, I have used the UML diagram of the Observer Design pattern.