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?
addObserver
is a method in the Observable
abstract class. See Observable in the Java documentation.Observable
. notifyObservers
will do nothing until setChanged
is set.Observer
is a common design pattern. The usual example is when you have a Model and multiple Views. Each View is an Observer on the Model; if the Model changes, the Views get updated.