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
Observermust overrideupdate. Theupdatemethod is called when theObservablecalls itsnotifyObserversmethod. - You “register” an
Observerwith the class that extendsObservableby callingaddObserveron it. You can add as manyObservers as needed. - The class that extends
Observablemust call the superclass’sObservable.setChangedmethod 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!