next up previous contents
Next: Proxy Pattern Up: Patterns used Previous: Patterns used   Contents

Observer Pattern

The "Status" and "Load" classes all extend the java.util.Observable class. This means, that whenever they are updated with new values, an Observer class is notified. This is done with the following two statements;
\begin{lstlisting}[frame=trbl,caption=Extract from Load.java]{}
setChanged();
notifyObservers();
\end{lstlisting}


The Spy class implements the java.util.Observer interface. This class observes the instances of "Load" and "Status" that are passed to it. To implement an Observer interface, you must inform the Observable class that it has an Observer. This can be done like this;
\begin{lstlisting}[frame=trbl,caption=Extract from Spy.java]{}
status.addObserver(this);
\end{lstlisting}


The public void update(Observable o, Object args) method must also be implemented. As the "Spy" class observes two different classes, polymorphism is used to distinguish between them, e.g.:


\begin{lstlisting}[frame=trbl,caption=Extract from Spy.java]{}
if(observable instanceof Names)
\end{lstlisting}


The observer pattern was implemented here because the "Spy" class must be kept updated at all times, as it is broadcast using RMI. The "Load" and "Status" classes should not have the responsibility of directly updating the object, as this is bad design. Using Observer here simplifies the design greatly, as updating is done automatically, and there is no need to pass the "Spy" class to the observable classes.


next up previous contents
Next: Proxy Pattern Up: Patterns used Previous: Patterns used   Contents
Colm O hEigeartaigh 2003-05-30