Reputation: 977
I am currently studying the observer patterns, but I am still confused on this set of codes:
public interface Observer {
public void update(String availability);
}
private ArrayList<Observer> observers = new ArrayList<Observer>();
Please help me to understand how Observer
interface runs on the ArrayList
.
Upvotes: 1
Views: 2661
Reputation: 1490
The code you have just provided is put in the object that can be observed (Observable: http://docs.oracle.com/javase/7/docs/api/java/util/Observable.html):
http://commons.wikimedia.org/wiki/File:Observer.svg
Once you have done that, when your Observable object state change, you call something like :
for(Observer o : observers)
{
o.update(null);
}
it notifies all observers that Observable has just changed.
Upvotes: 0
Reputation: 691685
An observer is an object that wants to be called when something has changed iin the observed object.
An ArrayList<Observer>
is simply a list containing 0, one or several observers. When the observed object needs to call its observers, it will thus iterate through the list and call each observer.
The mechanism is similar to promotional offers on web sites. The web site is the observed object. If you want to be notified when a promotional offer is created, you add yourself (you're thus an observer) to the list of persons to be notified. The web site keeps a list of persons to notify. And when the web site creates a new promotional offer, it iterates through the list of persons (observers) and sends an email to each of them.
Upvotes: 4