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?
The Java language supports the MVC architecture with two classes: Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.
You can use PropertyChangeEvent and PropertyChangeListener from java. beans package. PropertyChangeListener replaces Observer , but what should I extend/implement in place of Observable ?
Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.
Class Observable. Deprecated. This class and the Observer interface have been deprecated. The event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With