I'm trying to understand the Observer and the Observable.
Here's an example that I'm trying to figure out:
public class IntegerDataBag extends Observable implements Iterable<Integer> {
private ArrayList<Integer> list= new ArrayList<Integer>();
public void add(Integer i){
list.add(i);
setChanged();
notifyObservers();
}
public Iterator<Integer> iterator(){
return list.iterator();
}
public Integer remove (int index){
if (index< list.size()){
Integer i = list.remove(index);
setChanged();
notifyObservers();
return i;
}
return null;
}
}
public class IntegerAdder implements Observer {
private IntegerDataBag bag;
public IntegerAdder(IntegerDataBag bag) {
this.bag = bag;
bag.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o == bag) {
System.out.println("The contents of the IntegerDataBag have changed");
}
}
}
The bag.addObserver()
can be made only because IntegerDataBag
extends Observable
?
Where is this observer being add to? What is being created and where?
What is the difference between setChanged()
and notifyObservers()
?
I don't understand the update
method; what does arg
stand for? Why do I need to check that o==bag
? Why would I update another observable?
Why should I need this observer anyway?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…