Card 02/ 09

ConceptDifficulty: Intermediate1 min

Observer Pattern Structure: The Class and Sequence Diagrams

A Subject keeps a list of Observers and calls update() on each when its state changes.

Observer has two roles, each with an abstract and a concrete side: the subject that is watched and the observers that watch it. This card reads their roles off the Gang of Four's class diagram, then follows one change through a sequence diagram to show the order in which attach, change and notify happen.

Observer participants
Each participant and its role
ParticipantRole
SubjectKeeps the list of observers, and provides attach, detach and notify. It knows only the Observer interface.
ObserverDeclares update, the one method the subject calls.
ConcreteSubjectHolds the state observers care about, and calls notify when it changes.
ConcreteObserverReacts in update, often by reading the new state from the subject it was passed.
One change reaching two observers

The sequence diagram shows the pull form: update says only that something changed, and each observer asks the subject for what it needs. The alternative is the push form, where update carries the new data as an argument, such as the order that was placed. Push is simpler for observers and ties them less to the subject; pull suits observers that each need different parts of a large state.

The pull form is why the class diagram has an arrow from ConcreteObserver to ConcreteSubject: an observer that asks for the state must know the concrete class that holds it. The abstract Subject knows only the Observer interface, so new observers never change it.