Behavioral Patterns  «Prev 

Observer interface in java.util

The java.util package actually has an interface (or abstract class) called Observer and a class called Observable.
However, neither is much used, even though the delegation event model used in Java 1.1 makes heavy use of the Observer pattern.
The reason is that java.util.Observable is a class rather than an interface.
To use these two predefined bits of code your Observed object must extend Observable. In Java's single inheritance hierarchy, this is a huge impediment. This is one case where the abstract nature of the main classes is essential.

public interface Observer: A class can implement the Observer interface when it wants to be informed of changes in observable objects.
After applying the Observer pattern, different observers can be added dynamically without requiring any changes to the Subject class. Similarly, observers remain unaffected when the state change logic of the subject changes.


The Observer pattern is useful for designing a consistent communication model between a set of dependent objects and an object that they are dependent on. This allows the dependent objects to have their state synchronized with the object that they are dependent on. The set of dependent objects are referred to as observers and the object that they are dependent on is referred to as the subject.
In order to accomplish this, the Observer pattern suggests a publisher-subscriber model leading to a clear boundary between
  1. the set of Observer objects and
  2. the Subject object.

Below is an example written in Java that takes keyboard input and treats each input line as an event. The example is built upon the library classes
  1. java.util.Observer and
  2. java.util.Observable.
When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods, in this case represented as lambda function.

import java.util.Observable;
import java.util.Scanner;

class EventSource extends Observable implements Runnable {
 public void run() {
  while (true) {
   String response = new Scanner(System.in).next();
	 setChanged();
	 notifyObservers(response);
  }
 }
}