mercredi 3 avril 2019

Why ConcreteObserver holds a reference to ConcreteSubject in Observer Pattern?

Consider the diagram below.

Problem:

At page 294 of the Design Pattern book, Applicability's first item:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

Q1: If you want to "vary and reuse them independently", why did you bind ConcreteObserver to a ConcreteSubject?

No, this is not a question about implementation. When the author designed the diagram, he must had a general object-oriented idea in his mind, and I don't think they didn't notice it will cause coupling between ConcreteSubject and ConcreteObserver.

Q2: What's the purpose of Subject interface? Some books omit it.

No, this is not a question about implementation. I consider it a trade-off - the authors must have some idea about it, so he decide to make an interface for it, regardless that a ConcreteObserver holding a reference of ConcreteSubject means you might not need the interface at all, since you can't change it. But this is just my opinion.

For Q1, I think it's related one of the SOLID principle.
For Q2, I think it is to unify the interface of all concrete subjects, but the interface itself won't show in the code.

I need other point of view.

UML of Observer

Aucun commentaire:

Enregistrer un commentaire