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 Obs
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
Correct, Observable
is a class that has the addObserver()
method.
Where is this observer being add to? what being created and where?
The Observer
class contains a List
or Vector
(in the JDK source) of Observable
objects.
private Vector obs;
That's where it's stored.
What is the different between
setChanged()
andnotifyObservers()
?
The setChanged()
just marks the Observable
is changed.
The notifyObservers()
just calls the all observers it has on the list to update()
(passing a changed object to the Observer) only if the setChanged
is set to true.
I don't understand the update method- what does args stands for? and why do I need to check that o==bag, why would I update another observable?
The update()
method tells the Observer
that it needs to update based on the changed obj
it receives. This is called by the notifyObservers()
from Observable
.
Why should I need this observer anyway?
To create a Listener
for event driven scenario, i.e. if you want to be informed in the change of your observable objects, then Observer is needed.
Read: GoF - Observer pattern.