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:
- The class that implements
Observer
must overrideupdate
. Theupdate
method is called when theObservable
calls itsnotifyObservers
method. - You “register” an
Observer
with the class that extendsObservable
by callingaddObserver
on it. You can add as manyObserver
s as needed. - The class that extends
Observable
must call the superclass’sObservable.setChanged
method prior to callingnotifyObservers
, otherwise no notification will be sent to theObserver
.
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 |
|
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!