1. Extend an Observable
Your class need to extend Observable and provide some mechanism for adjusting and accessing the internal state of the observable object.
Here, internal state is managed by the integer n. If this value is changed, the observable object invokes its own setChanged() method and then invokes its 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;
}
}
2. Implement an Observer
Class that observe the changes in state of another object implements the Observer interface and provide an update() method.
The update method is called whenever the observable changes state and announces this fact by calling its notifyObservers() method.
import java.util.Observer;
import java.util.Observable;
public class TextObserver implements Observer {
private ObservableValue ov = null;
public TextObserver(ObservableValue ov) {
this.ov = ov;
}
public void update(Observable obs, Object obj) {
if (obs == ov) {
System.out.println(ov.getValue());
}
}
}
3. Tie the two together
ObservableValue ov = new ObservableValue(0);
TextObserver to = new TextObserver(ov);
ov.addObserver(to);
How it all works together ?
1. Controller makes a change to the model via accessor method - setValue() in the example.
2. Accessor modifies the data, calls its setChanged() method to indicate that its state has changed and then calls notifyObservers() to notify the observers that it has changed.
3. The update() method on each of the observers are called, indicating that a change in state has occurred.
The observers access the data via the model's public accessor methods and update their respective views.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.