observer pattern fall 2005 oopd john anthony. what is a pattern? “each pattern describes a problem...

21
Observer Pattern Observer Pattern Fall 2005 OOPD Fall 2005 OOPD John Anthony John Anthony

Post on 19-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer Pattern Observer Pattern

Fall 2005 OOPDFall 2005 OOPDJohn AnthonyJohn Anthony

Page 2: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

What is a Pattern?What is a Pattern?

““Each pattern describes a problem Each pattern describes a problem which occurs over and over again in which occurs over and over again in our environment, and then describes our environment, and then describes the core of the solutions to that the core of the solutions to that problem, in such a way that you can problem, in such a way that you can use this solution a million times use this solution a million times over, without ever doing it the same over, without ever doing it the same way twice.” way twice.” Christopher Alexander.Christopher Alexander.

Page 3: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

The Pattern of a PatternThe Pattern of a Pattern Pattern NamePattern Name

provides high levels of abstractionprovides high levels of abstraction Problem DefinitionProblem Definition

when to apply the patternwhen to apply the pattern SolutionSolution

the elements that make up the pattern the elements that make up the pattern and their relationships.and their relationships.

ConsequencesConsequencesthe results and tradeoffs of the pattern.the results and tradeoffs of the pattern.

Page 4: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer PatternObserver Pattern

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

Example: Graphical editor with multiple Example: Graphical editor with multiple views of the same graphic objects. If a views of the same graphic objects. If a graphical object is manipulated in one graphical object is manipulated in one view, it notifies the other views to view, it notifies the other views to display the changes made to it.display the changes made to it.

Page 5: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Key BehaviorsKey Behaviors

A common side-effect of partitioning a system into a A common side-effect of partitioning a system into a collection of cooperating classes is the need to collection of cooperating classes is the need to maintain consistency between related objects. maintain consistency between related objects.

The key objects in the Observer pattern are Subject The key objects in the Observer pattern are Subject and Observer. and Observer.

A subject may have any number of dependent A subject may have any number of dependent observers. observers.

All observers are notified whenever the subject All observers are notified whenever the subject undergoes a change in state. undergoes a change in state.

In response, each observer will query the subject to In response, each observer will query the subject to synchronize its state with the subject´s state.synchronize its state with the subject´s state.

Page 6: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

When to Use the Observer When to Use the Observer PatternPattern

Use the Observer pattern in any of the Use the Observer pattern in any of the following situationsfollowing situations When an abstraction has two aspects, one When an abstraction has two aspects, one

dependent on the other. Encapsulating dependent on the other. Encapsulating these aspects in separate objects lets you these aspects in separate objects lets you vary and reuse them independtly.vary and reuse them independtly.

When a change to one object requires When a change to one object requires changing others, and you do not know how changing others, and you do not know how many objects need to be changed.many objects need to be changed.

When an object should be able to notify When an object should be able to notify other objects without making assumptions other objects without making assumptions about who these objects are.about who these objects are.

Page 7: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Class DiagramClass Diagram

Page 8: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer ParticipantsObserver Participants

SubjectSubject Knows its observers. Any numberof Knows its observers. Any numberof

Observer objects may observe a subject.Observer objects may observe a subject. Provides an interface for attaching and Provides an interface for attaching and

detaching Observer Objects.detaching Observer Objects. ObserverObserver

Defines an updating interface for objects Defines an updating interface for objects that should be notified of changes in a that should be notified of changes in a subjectsubject

Page 9: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer ParticipantsObserver Participants

ConcreteSubjectConcreteSubject Stores a state of interest to ConcreteObserver objects.Stores a state of interest to ConcreteObserver objects. Sends a notification to its observers when its state Sends a notification to its observers when its state

changes.changes. ConcreteObserverConcreteObserver

Maintains a reference to a ConcreteSubject objectMaintains a reference to a ConcreteSubject object Stores state that should stay consistent with the Stores state that should stay consistent with the

subject state.subject state. Implements the Observer updating interface to keep Implements the Observer updating interface to keep

its state consistent with the subject state.its state consistent with the subject state.

Page 10: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer CollaborationsObserver Collaborations

ConcreteSubject notifies its observers ConcreteSubject notifies its observers whenever a change occurs that could whenever a change occurs that could make its observer’s state inconsistent make its observer’s state inconsistent with its own.with its own.

After being informed of a change in the After being informed of a change in the ConcreteSubject, a ConcreteObserver ConcreteSubject, a ConcreteObserver object may query the subject for object may query the subject for information. ConcreteObserver uses this information. ConcreteObserver uses this information to reconcile its state with information to reconcile its state with that of the object.that of the object.

Page 11: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Sequence DiagramSequence Diagram

Page 12: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Sequence Diagram NotesSequence Diagram Notes

Note that the Observer object that Note that the Observer object that initiates the change request with initiates the change request with SetState() postpones its update until it SetState() postpones its update until it gets a notification from the subject.gets a notification from the subject.

In this scenario Notify() is called by the In this scenario Notify() is called by the subject, but it can be called by an subject, but it can be called by an observer or by another kind of object observer or by another kind of object (see implementation issues)(see implementation issues)

Page 13: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Pattern ConsequencesPattern Consequences

The Observer pattern lets you vary The Observer pattern lets you vary subjects and observers independently. subjects and observers independently. You can reuse subjects without reusing You can reuse subjects without reusing observers, and vice versa. It lets you observers, and vice versa. It lets you add observers without modifying the add observers without modifying the subject or other observers.subject or other observers.

Page 14: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Consequences (Con’t)Consequences (Con’t) Abstract coupling between Subject and Abstract coupling between Subject and

ObjectObject All a subject knows is that it has a list of All a subject knows is that it has a list of

observers, each conforming to the simple observers, each conforming to the simple interface of the abstract Observer class. The interface of the abstract Observer class. The subject does not know the concrete class of subject does not know the concrete class of any observer.any observer.

Support for broadcast communicationSupport for broadcast communication Unlike and ordinary request, the notification Unlike and ordinary request, the notification

that a subject sends need not specify its that a subject sends need not specify its receiver. The notification is broadcast receiver. The notification is broadcast automatically to all interested objects that automatically to all interested objects that subscribed to it.subscribed to it.

Page 15: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Unexpected UpdatesUnexpected Updates Because observers have no knowledge of each Because observers have no knowledge of each

other’s presence, they can be blind to the other’s presence, they can be blind to the ultimate cost of changing the subject. A ultimate cost of changing the subject. A seemingly innocuous operation to the subject seemingly innocuous operation to the subject may cause a cascade of updates to observers may cause a cascade of updates to observers and their dependent objects. and their dependent objects.

This problem is aggravated by the fact that the This problem is aggravated by the fact that the simple update protocol provides no details onsimple update protocol provides no details on what what changed in the subject. Without additional changed in the subject. Without additional protocol observers have to query the entire state protocol observers have to query the entire state of the subject to deduce the changes.of the subject to deduce the changes.

Consequences (Con’t)Consequences (Con’t)

Page 16: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer Observer ImplementationImplementation

Mapping subjects to their oberversMapping subjects to their obervers

The simplest way for a subject to keep The simplest way for a subject to keep track of the obervers it should notify is track of the obervers it should notify is to store references to them explicitly in to store references to them explicitly in the subject. An alternative is to use an the subject. An alternative is to use an associative look-up (multimap) to associative look-up (multimap) to maintain the subject-observer mapping.maintain the subject-observer mapping.

Page 17: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer Observer ImplementationImplementation

Observing more than one subjectObserving more than one subject

It might make sense in some situations for an It might make sense in some situations for an observer to depend on more than one subject. observer to depend on more than one subject. It is necessary to extend the Update interface It is necessary to extend the Update interface in such cases to let the observer knowin such cases to let the observer know which which subject is sending the notification. The subject subject is sending the notification. The subject can simply pass itself as a parameter in the can simply pass itself as a parameter in the Update operation, thereby letting th observer Update operation, thereby letting th observer know which subject to examine.know which subject to examine.

Page 18: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Who triggers the updateWho triggers the update The subject and its observers rely on The subject and its observers rely on

the notification mechanism to stay the notification mechanism to stay consistent. But what object actually consistent. But what object actually calls Notify() to trigger the update? calls Notify() to trigger the update? There are two options.There are two options.

Have state-setting operations on the Have state-setting operations on the Subject call Notify after they change Subject call Notify after they change the subject’s statethe subject’s state

Make clients responsible for calling Make clients responsible for calling Notify at the right time.Notify at the right time.

Observer Observer ImplementationImplementation

Page 19: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Subject calls NotifySubject calls Notify The advantage of this approach is that clients do The advantage of this approach is that clients do

not have to remember to call Notify on the not have to remember to call Notify on the subject. The disadvantage is that several subject. The disadvantage is that several consecuitve operations will cause several consecuitve operations will cause several consecutive updates, which may be inefficientconsecutive updates, which may be inefficient

Clients calls NotifyClients calls Notify The advantage here is that the client can wait to The advantage here is that the client can wait to

trigger the update until after a series of state trigger the update until after a series of state changes has been made. The disadvantage is changes has been made. The disadvantage is that clients have an added responsibility to that clients have an added responsibility to trigger the update, causing possible errors.trigger the update, causing possible errors.

Observer Observer ImplementationImplementation

Page 20: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Observer Observer ImplementationImplementation

Avoiding observer-specific update Avoiding observer-specific update protocols : the push and pull modelprotocols : the push and pull model Implementations of the Observer pattern Implementations of the Observer pattern

often have the subject broadcast additional often have the subject broadcast additional information about the change. The subject information about the change. The subject passes this information as an argument to passes this information as an argument to Update. Update.

Push model: the subject sends obervers Push model: the subject sends obervers detailed information about the changedetailed information about the change

Pull model: the subject sends only a Pull model: the subject sends only a minimal notification and observers ask for minimal notification and observers ask for details explicitlydetails explicitly

Page 21: Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,

Pull model:Pull model: The pull model emphasizes the subject’s ignorance The pull model emphasizes the subject’s ignorance

of its obervers. The pull model may be inefficient, of its obervers. The pull model may be inefficient, because Observer classes must infer what changed because Observer classes must infer what changed without help from Subject.without help from Subject.

Push model:Push model: The push model assumes that the subject knows The push model assumes that the subject knows

something about its obervers’ needs.something about its obervers’ needs. The push model might make observers less reusable The push model might make observers less reusable

because Subject classes make assumptions about because Subject classes make assumptions about Observer classes that might not always be true.Observer classes that might not always be true.

Observer Observer ImplementationImplementation