Вы находитесь на странице: 1из 8

Observer

Intent Define one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Motivation Having abstraction of two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

Solution
Subject
1

Observer
*

+Attach(in Observer) +Detach(in Observer) +Notify()

for All in O in observers { O->Update(); }

+Update()

ConcreteSubject
-subjectState +GetState() +SetState()

ConcreteObserver
-observerState +Update()

return subjectState;

observerState = subject->GetState();

Sequence Diagram
<<Actor>> Client ConcreteSubject ConcreteObserver1 ConcreteObserver2

1 : setState()

2 : notify() 3 : update()

4 : getState() 5 : update()

6 : getState()

Variation
Mapping subjects to their observers. Observing more than one subject. The Update function can have subject as its parameter to let the Observers identify the subjects. Who triggers the update? The subject or the observer or the client. The Notify is not always called by the subject, it can be called by an observer or by another kind of object entirely. Push model: The subject sends observer detailed information.

Variation Continues Pull model: The subject sends nothing more than notification. The observer pull needed information. Specifying modifications of interest explicitly: notifying only a subset of observers that are interested in a particular event. Encapsulating complex update semantics: When the dependency relationship between subjects and observers is particularly complex, an object that maintains these relationships might be required and such an object is called Change Manager.

Example

Subject
-List<Observer*> +Attach(in Observer) +Detach(in Observer) +Notify()
1 1

Widget +Draw()

Observer +Update()

ClockTimer
+GetHour() +GetMinute() +GetSecond() +Tick()

11 *

DigitalClock
-ClockTimer* sub +Draw() +Update(in Subject Chsub)
1

AnalogClock
-Clocktimer* sub +Draw() +Update(in Subject * Chsub)
1 *

while(1) { //Global Function ClockTickchange(); notify(); }

if (ChSub = sub) { Draw(); }

Consequences
Abstract coupling between Subject and Observer. Unexpected updates is unavoidable if one of the observer itself notify the subject for a change in state. If changes in state happens very frequently, it loads the subject/observer heavily and which may degrade the performance of the overall software application/product.

Where/how we can apply this pattern in our product design?

Вам также может понравиться