Question

In the observer design pattern I know we have to register the observer with the subject. But i have noticed that in some implementations the subject instance is send through the observer class and then the object of observer is send to Subject class using the instance of subject. See the example below

public class Observer1 extends Observer {

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

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

My question is does the Observer class need to have the subject instance? I thought Observer was totally decoupled from the subject

Could someone give me a good implementation of Observer design pattern or any resources

Was it helpful?

Solution

Theoretically the Observer does not need to keep the reference of the Observable object (what you call 'Subject') in a field, since the Observer normally already receive the Observable object as a parameter of the update method.

OTHER TIPS

That is a poor implementation of the Observer pattern. The Subject (or Observable) should have a set of Observers, and needs to know nothing more about them than how to notify them of changes to it's state.

Any changes to the Observable's state can be propagated via a parameter in the notification mechanism; this is why Java's Observable has an extra parameter in it's notifyObservers(Object) method.

The Observer should not need anything more than it's update method, to be called by notifyObservers. Note that in the Java SDK, the update method is given a reference to the Observable as a parameter, so there is no need to make this a data member of the Observer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top