Search code examples
design-patternsobserver-pattern

Observer Design Pattern - Concrete Subjects and Observers


The references (GOF Design Patterns, Head First Design Patterns, http://www.dofactory.com/Patterns/PatternObserver.aspx) that I've read regarding the observer design pattern stipulate that the concrete subject holds a reference to the concrete observer. Much like this:

class ConcreteObserver : IObserver
{
    ConcreteSubject concreteSubjectInstance;
    //other code, etc.
} 

Now, if the concrete Subject is itself implements a Subject interface (or derives from some abstract Subject class) why not make the type in the ConcreteObserver be of that abstract/interface? I.e.

class ConcreteObserver : IObserver
{
    ISubject concreteSubjectInstance;
    //other code, etc.
} 

Moreover, why not just make it a field in the (e.g.) IObserver interface?

Ultimately, given that the pattern itself seems to loosen the coupling of the Subject to its Observers, why does this appear not to be promoted when coupling an Observer to its subject?

enter image description here

Or is it? I am only basing this on examples that I have read.


Solution

  • From your picture, your "update()" method does not receive any information about the state of the Subject, so, if the Observer needs information about this state (as usual in the observer pattern), then it must retrieve it from the ConcreteSubject invoking to the "GetState()" method (not present in ISubject).

    An alternative to this schema, would be to pass the state (or a reference to the whole ConcreteSubject) as parameter of "update()" method.

    Other general explanations to having a reference to ConcreteSubject instead of ISubject can be that you may want to interact with the ConcreteSubject to invoke business logic (of course not exposed in the ISubject interface).