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 theSubject
in detail theSubject
knows onlyObservers
. To be more precise theSubject
doesn't know the details about yourBinaryObserver
it can only send messages to it that are defined in theObserver
class. In that waySubject
is decoupled from the details of yourBinaryObserver
class.To sum up, while the coupling of the
BinaryObserver
to theSubject
is very high the coupling in the opposite direction is weak.