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 becauseIntegerDataBagextendsObservable?Where is this observer being add to? What is being created and where?
What is the difference between
setChanged()andnotifyObservers()?I don't understand the
updatemethod; what doesargstand for? Why do I need to check thato==bag? Why would I update another observable?Why should I need this observer anyway?