Observer Pattern

1 minute read

Hey Subject, I would like to register myself to your subscribers list. Please update me too when your state changes. Thank you. Observer class

This is a continuation of the software design pattern series.

Observer pattern

Ever been in a situation where if one object’s state changes, you need some other objects to change their behavior and state too? Then, Observer pattern is your weapon from the armory.

Ok. So how to solve?

Publishers + Subscribers = Observer Pattern.
If you understand newspaper subscriptions, you pretty much understand the Observer Pattern, only we call the publisher the SUBJECT and the subscribers the OBSERVERS.

In Software design it goes like
Publisher: The object which is to be watched.
Subscriber: The object which needs to be reflected when a publisher’s state changes.
Here the publishers and subscribers are loosely coupled thus making them work independently and they don’t need to know each other exclusively.

Example 1: You have a set of data and whenever it is updated, you need to update the grid display, graph display, third party display and so on.

Example 2: A photo is posted in your social network and all the respective person’s followers should be getting a notification.

Cool. So how to actually implement it?

In Observer pattern, 4 different components gets involved excluding the Client.

  • Subject interface/abstract class
  • Concrete Subject
  • Observer interface
  • Concrete Observer

-> Subject interface

This abstract class or interface has the methods for registering and de-registering of observers.

-> Concrete Subject class

The class which implements the Subject interface. This maintains the state of the Subject object and takes care of notifying all its observers by calling their update() method.

-> Observer interface

The interface which all the observers need to implement. This has the update() method which the implementing classes have to implement.

-> Concrete Observer

The class implementing the Observer interface. This has their own implementation of the update() method which will be triggered by the observer.

Design Structure

image tooltip here

photo courtesy: link

Sample code

As seen in the code example when DataStore’s setData is called from client, all the observers of the DataStore subject are getting notified and their respective update() method is called. Thus when observer’s state changes, all the subscribed observers are getting informed.

Thank you. Hope this helps. Looking forward to more learning and sharing. Cheers :)

Stay connected:

Connect on Twitter

Connect on Linkedin