Search code examples
javaobserver-pattern

What is this line of code producing?


I have been studying the observer pattern from head_first_design_Patterns book. The scenario is this " there is an ArrayList named as observers and it has all the observers that are implementing the Observer interface. In the book,they are using a loop to update all the observers. The loop is:

 for(int i=0; observers.size();i++)
 {
     Observer observer= (Observer) observers.get(i);
     observer.update(temperature,humidity,pressure);
 } 

I want to know how is the first statement of loop is working. Are we creating references to a particular observer here?


Solution

  • I want to know how is the first statement of loop is working. Are we creating references to a particular observer here?

    This statement simply gets the element within the ArrayList at the specified index and makes sure that its an Observer type before pointing the reference to the retrieved object.

    Observer observer= (Observer) observers.get(i);
    

    If the cast is successful then the reference to the retrieved object gets used to update the data for that particular object.

    observer.update(temperature,humidity,pressure);