Observer Pattern and Circular References

observer-pattern

I was checking this example of Observer Pattern.

https://www.tutorialspoint.com/design_pattern/observer_pattern.htm

It seems that there is a circular reference when Observer Pattern is used.

import java.util.ArrayList;
import java.util.List;
public class Subject {

   private List<Observer> observers = new ArrayList<Observer>();
   private int state;

   public int getState() {
      return state;
   }

   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }

   public void attach(Observer observer){
      observers.add(observer);      
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   }    
}


public class BinaryObserver extends Observer{

  public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); 
   }
}

I am not posting all the other code, but from the initial look it seems that such design will almost always have a circular reference. Am I misunderstanding anything here?

Thanks,

Best Answer

Yes, you are right. Both objects know each other if that is what your are referring to. The important thing is what they know about each other. While the BinaryObserver knows the Subject in detail the Subject knows only Observers. To be more precise the Subject doesn't know the details about your BinaryObserver it can only send messages to it that are defined in the Observer class. In that way Subject is decoupled from the details of your BinaryObserverclass.

To sum up, while the coupling of the BinaryObserver to the Subject is very high the coupling in the opposite direction is weak.

Related Topic