Page 3 of 5
The following are code listings for observer and observable functions:
Observer
public void update(Observable obs, Object obj)Observable
public void addObserver(Observer obs)public void deleteObserver(Observer obs)public void deleteObservers()public int countObservers()protected void setChanged()state.
protected void clearChanged()changed state.
public boolean hasChanged()state.
public void notifyObservers()state and notifies all observers.
public void notifyObservers(Object obj)state and notifies all observers. Passes the object specified in the
parameter list to the notify() method of the observer.
The following section describes in detail how to create a new observable class and a new observer class, and how to tie the two together.
A new class of observable objects is created by extending class Observable. Because class Observable already implements all of the methods necessary to provide the observer/observable behavior, the derived class need only provide some mechanism for adjusting and accessing the internal state of the observable object.
In the class ObservableValue listing below, the internal state of the model is captured by the integer n. This value is accessed (and, more importantly, modified) only through public accessors. If the value is changed, the observable
object invokes its own setChanged() method to indicate that the state of the model has changed. It then invokes its own notifyObservers() method in order to update all of the registered observers.
import java.util.Observable;
public class ObservableValue extends Observable
{
private int n = 0;
public ObservableValue(int n)
{
this.n = n;
}
public void setValue(int n)
{
this.n = n;
setChanged();
notifyObservers();
}
public int getValue()
{
return n;
}
}
A new class of objects that observe the changes in state of another object is created by implementing the Observer interface.
The Observer interface requires that an update() method be provided in the new class. The update() method is called whenever the observable changes state and announces this fact by calling its notifyObservers() method. The observer should then interrogate the observable object to determine its new state, and, in the case of the Model/View/Controller
architecture, adjust its view appropriately.
Very helpful, thanks!By Anonymous on July 20, 2009, 1:52 pmVery helpful, thanks!
Reply | Read entire comment
GreatBy Anonymous on July 2, 2009, 12:23 amIt gives a very good description. but i wanted some implementation code also
Reply | Read entire comment
ExcelentBy Anonymous on January 30, 2009, 2:00 amI got very clear idea onthis topic after reading this
Reply | Read entire comment
View all comments