Summary: A very simple example of the Observer / Observable pattern in Java
In my example, a class called
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
updatemethod is called when the
- You “register” an
Observerwith the class that extends
addObserveron it. You can add as many
Observers as needed.
- The class that extends
Observablemust call the superclass’s
Observable.setChangedmethod prior to calling
notifyObservers, otherwise no notification will be sent to the
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!