mdoery ~ software development

adventures in coding

Observer / Observable pattern in Java

| Comments

Summary: A very simple example of the Observer / Observable pattern in Java

I’ve created a very simple example of the Observer pattern using Java’s built-in Observable class and Observable interface.

In my example, a class called ObservableExample extends Observable. It has a method called setCookie which is used to set a String with the name of a cookie such as “Chocolate chip”. When this method is called, its Observer is intended to do something – in this example, it prints a message about what beverage accompanies each type of cookie.

There are three key pieces to this pattern:

  1. The class that implements Observer must override update. The update method is called when the Observable calls its notifyObservers method.
  2. You “register” an Observer with the class that extends Observable by calling addObserver on it. You can add as many Observers as needed.
  3. The class that extends Observable must call the superclass’s Observable.setChanged method prior to calling notifyObservers, otherwise no notification will be sent to the Observer.

Here’s a skeleton of the code, showing all the important parts without implementation details:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ObserverExample implements Observer {
  public void update(Observable obs, Object arg) {
      // Do something depending on arg and/or obs
  }
}

class ObservableExample extends Observable {
  public void someImplementationSpecificMethod(...) {
      setChanged(); // method of Observable superclass.
      notifyObservers(...); // causes update method to be called on any Observers
  }
}

...
// In other code, e.g. main method:
ObservableExample observable = new ObservableExample();
ObserverExample observer = new ObserverExample();
observable.addObserver(observer);
// later...
observable.someImplementationSpecificMethod(...);

This code sample is available as a project in github. That project contains an additional code example which abstains from using Java’s Observable class and Observer interface. This demonstrates that you can do what you want without those tools. However, you have to introduce additional code to manage the notification into your own classes. This makes the code more cluttered, and less clear. Our little demo project is all about serving the right hot beverage with a given cookie. Using the Observer pattern abstracts away functionality which is not crucial to this purpose!

Comments