Java Reference
In-Depth Information
protected void clearChanged()
boolean hasChanged()
void notifyObservers()
void notifyObservers(Object arg)
protected void setChanged()
The Observer interface defines only one method— void update(Observable o, Object arg)
which will be called by the subject. This is illustrated with an example. Say you are building an
application to fetch stock quotes. At one point, you realize that other applications might want to
plug in to your code to register an interest to be notified whenever you pull in a new stock quote.
You decide to make the relevant class in your code Observable :
import java.util.Observable;
// Observable class (the subject)
public class StockTicker extends Observable {
public void updateStock() {
// Stock retrieving code here
// At the end, we get a Quote object, which we pass to our observers
Quote latestStockQuote = ...;
notifyObservers(latestStockQuote);
}
}
Note the notifyObservers call. Observers can now be implemented as a class like so:
import java.util.Observable;
import java.util.Observer;
public class StockObserver implements Observer {
@Override
public void update(Observable sender, Object receivedObject) {
Quote quote = (Quote) receivedObject;
// Do something interesting with the quote here
}
}
Before getting updates from the subject, observers have to register themselves, like so:
public static void main(String[] args) {
StockTicker ticker = new StockTicker();
StockObserver observer = new StockObserver();
ticker.addObserver(observer);
// Add other observers
}
Search WWH ::




Custom Search