Observer Pattern

Pattern

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they're "observing."

Given the COVID-19 crisis, this example seems relevant: suppose you are interested in purchasing "disinfecting wipes" but it is out of stock. You would want to keep an eye out for when it becomes available again; you may routinely check the stocks (by visiting your local store or your favorite online shopping website). This will require a significant time, commitment and effort on your side. A better strategy is to subscribe (if that option is available) to your provider subscription service and ask to be notified when the item of interest becomes in-stock.

Observer design pattern is also called as publish-subscribe pattern. It allows you get notified whenever there is a change in the state of an object you are interested in.

In observer pattern, the object that watch on the state of another object are called Observer and the object that is being watched is called Subject.

This pattern is widely applied to Graphical User Interface (GUI) components through Action/Event Listener. The idea is to consider each GUI component a subject where different events (e.g. clicking on) would send a notification to an observer class (typically called an Event Listener) which would perform different actions based on the occurrence of an event.1

Java facilitates implementing Observer pattern through Observable class and Observer interface.2 The subject class must extend Observable and observers must implement Observer. Here is a simplified UML diagram that represents the Observer pattern in Java:

The use of Observer (as a separate interface with just one method) is in line with the Interface Segregation Principle. Moreover, it is in accordance to the Open/Closed principle; you can add multiple new types of observes and add them to subject (observable) without minimized risk of breaking the application.

When to use this pattern?

Use the Observer pattern when changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand (or changes dynamically).

Advantage

Observers are loosely coupled to subject since the Subject knows nothing about them, other than that they implement the Observer interface.


  1. Java's EventListener in Swing implements the Observer pattern. 

  2. The Observable class and the Observer interface have been deprecated in Java 9. This does not mean the Observer Pattern is depreciated! The pattern is extremely useful. The implementation of the pattern in Java, however, was not ideal (lack of thread safety, not Serializable, limited event model, ...). So, as a Java developer you may want to consider implementing the pattern yourself or using other mechanisims in Java (e.g. java.beans) for a notification model.