0

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?

Haris
  • 764
  • 4
  • 9
  • 27
  • Possible duplicate of [When should we use Observer and Observable](http://stackoverflow.com/questions/13744450/when-should-we-use-observer-and-observable) – Ravi Mar 12 '17 at 12:22
  • Yes, you are getting a reference to the object that `observers.get(i)` returns. You are casting this object to an `(Observer)`, and then you can operate on it using the local variable `observer`. – uvesten Mar 12 '17 at 12:23
  • @Ravi: I don't think the question has anything to do with the question you linked. – uvesten Mar 12 '17 at 12:24
  • @uvesten I just pointed that question to first have a look in that question. As, that question has code mentioned related to this Design Pattern – Ravi Mar 12 '17 at 12:28

3 Answers3

2

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);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

Yes, you are getting a reference to the object that observers.get(i) returns. You are casting this object to (Observer), and then you can operate on it using the local variable observer.

uvesten
  • 3,365
  • 2
  • 27
  • 40
0

The first line just fetch the observer from the list. It creates a new reference to an existing object

fer.marino
  • 497
  • 1
  • 5
  • 20