Observer pattern

Prakash Sharma
2 min readJan 10, 2023

--

This is 7th pattern in the series of must-know design patterns. It is the most common design pattern one developer uses in day-to-day life. Every developer must have used this in one or another way.

Problem: Let’s say we have to implement an Excel sheet with a chart and a sheet with some formula features. If there is any change in the data source the chart and sheet should be updated accordingly.

A brute-force solution would be something like where the data class will have reference to the spreadsheet and chart class so whenever there is a data change it will update the spreadsheet and chart. But this way coupling between the code will increase and also if there are more sheets and charts in the future then this solution will break.

Solution:

An observer pattern is a behavioral design pattern based on a publish-subscribe model. The publisher publishes the changes to the objects observing it. The publisher is also known as Observable and the subscriber is also known as the observer.

There is an interface Observer which will be implemented by the classes which want to listen for the changes in the observables/data source. The interface is something like -

Let’s see the concreate implementations -

Our data source will be like —

We can also have an interface for data sources which will be known as observable. Here, for simplicity, I have removed that step. That would be useful if you have more than one observables to observe.

Let’s see the result of the above code

The output is —

Updating spreadsheet with data = 30
Updating chart with value 30

See in you my next blog on mediator patterns. Till then happy coding. Do not forget to clap.

My previous design pattern blogs —

--

--