Observer Pattern in Java [Example]

Click an image to enlarge.

Runnable Observable Class example:

This is the class that is the core of our program. As we’re using it threaded, this class implements Runnable. Because we also want to know when it actually is running, it extends Observable. By doing so, we can change the GUI when the ‘engine’ class is in the ‘running’ status, we don’t know when this will be. The thread manager will pick the execution time, not us.
When the engine class goes into run(), and if it doesn’t fail to open the ServerSocket in our example, it will setChanged() and notifyObservers(). [our observer in this example is DomainController]

Observable Runnable Class

DomainController Observer/Observable Class example:

Our DomainController is both an Observer of the Engine Class and Observable from our GUI.
When the engine gets made, we add the DomainController as observer. [getDeamon().addObserver(this)]
When the DomainController gets message from the engine (update method), it will setChanged() and notifyObservers().

Observable/Observer DomainController Class

Observer GUI Class example:

On creation, we know the DomainController. We add our GUI elements as observers. [dc.addObserver(this)]
When the DomainController notifies them, they’ll run the update method. In our example, we update the GUI elements using updateAll() in the JFrame and reloadInfo() in the Tray.

Observer GUI Class

To download the whole project, you can use a svn client to ‘checkout http://httpdragon.googlecode.com/svn/trunk/‘.

Leave a Reply