1

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.

2
  • 2
    What do you mean by "Observer interface runs on the ArrayList"? Commented Oct 29, 2013 at 13:09
  • if i understand your question, then all of the observed objects has to be notified, so you should iterate through whole arraylist Commented Oct 29, 2013 at 13:10

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.