0% found this document useful (0 votes)
4 views

Observer Pattern

Uploaded by

alitigercr71381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Observer Pattern

Uploaded by

alitigercr71381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Observer Design Pattern

Dr. Abbas Rasoolzadegan


Problem

1
Observer Pattern
 The key objects in this pattern are subject and observer.
 A subject may have any number of dependent observers.
 All observers are notified whenever the subject undergoes a
change in state.
 In response, each observer will query the subject to synchronize its
state with the subject's state.
 This kind of interaction is also known as publish-subscribe.
 The subject is the publisher of notifications.
 It sends out these notifications without having to know who its
observers are.
 Any number of observers can subscribe to receive notifications.

2
Applicability
Use the Observer pattern in any of the following situations:
 When an abstraction has two aspects, one dependent on the other.
Encapsulating these aspects in separate objects lets you vary and
reuse them independently.
 When a change to one object requires changing others, and you
don't know how many objects need to be changed.
 When an object should be able to notify other objects without
making assumptions about who these objects are. In other words,
you don't want these objects tightly coupled.

3
Structure
In the Mediator pattern colleagues can communicate with the mediator
using the Observer pattern: Explain the solution in details.

4
Collaborations

5
Sample Code
class Subject {
public:
virtual ~Subject();
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify();
protected:
Subject();
private:
List<Observer*> *_observers;
};

6
Sample Code (cont.)
class Subject;
class Observer {
public:
virtual ~Observer();
virtual void Update(Subject* theChangedSubject)=0;
protected:
Observer();
};

7
Sample Code (cont.)
void Subject::Attach(Observer* o) {
_observers->Append(o);
}
void Subject::Detach(Observer* o) {
_observers->Remove(o);
}
void Subject::Notify() {
ListIterator<Observer*> i(_observers);
for (i.First(); !i.IsDone(); i.Next()) {
i.CurrentItem()->Update(this);
}
}
Java has built-in support for Observer: Explain with an example.
8
Implementation Issues
 Mapping subjects to their observers.
 The simplest way for a subject to keep track of the observers it should
notify is to store references to them explicitly in the subject.
 However, such storage may be too expensive when there are many
subjects and few observers. One solution is to trade space for time by
using an associative look-up (e.g., a hash table) to maintain the
subject-to-observer mapping. (Why??)
 Observing more than one subject.
 It might make sense in some situations for an observer to depend on
more than one subject.
 It's necessary to extend the Update interface in such cases to let the
observer know which subject is sending the notification.
 The subject can simply pass itself as a parameter in the Update
operation, thereby letting the observer know which subject to
examine.
9
Implementation Issues (cont.)
Who triggers the update?
 The subject and its observers rely on the notification mechanism to
stay consistent. But what object actually calls Notify to trigger the
update? Here are two options:
 Have state-setting operations on Subject call Notify after they change
the subject's state. The advantage of this approach is that clients don't
have to remember to call Notify on the subject. The disadvantage is
that several consecutive operations will cause several consecutive
updates, which may be inefficient.
 Make clients responsible for calling Notify at the right time. The
advantage here is that the client can wait to trigger the update until
after a series of state changes has been made, thereby avoiding
needless intermediate updates. The disadvantage is that clients have an
added responsibility to trigger the update. That makes errors more
likely, since clients might forget to call Notify.
10
Implementation
 Subject calls Notify:
void ConcreteSubject::setstate(int newstate) {
state_ = newstate;
// notify all observers that state has changed
notify();
}
Subject s1;
s1.setstate(6);
// automatic call to notify
s1.setstate(5);
// automatic call to notify

11
Implementation (cont.)
 Observer or client calls Notify:

void ConcreteSubject::setstate(int newstate)


{
state_ = newstate;
}

Subject s1;
s1.setstate(6);
s1.setstate(5);
s1.notify(); // explicit call to notify

12
Implementation (cont.)
 Dangling references to deleted subjects.
 Deleting a subject should not produce dangling references in its
observers. One way to avoid dangling references is to make the
subject notify its observers as it is deleted so that they can reset
their reference to it. In general, simply deleting the observers is
not an option, because other objects may reference them, or
they may be observing other subjects as well.
 The push & pull model:
 Push Model: the subject sends observers detailed information
about the change, whether they want it or not.
 Pull Model: the subject sends nothing but the most minimal
notification, and observers ask for details explicitly thereafter.
13
Implementation (cont.)
 Specifying modifications of interest explicitly.
 The subject informs only those observers that have registered
interest in that event.
 One way to support this is to use the notion of aspects for Subject
objects.
 To register interest in particular events, observers are attached to
their subjects using:
void Subject::Attach(Observer*,Aspect& interest);
 Interest specifies the event of interest. At notification time, the
subject supplies the changed aspect to its observers as a parameter
to the Update operation.

14
ChangeManager
 Encapsulating complex update semantics.
 When the dependency relationship between subjects and observers
is particularly complex, an object that maintains these relationships
might be required. We call such an object a ChangeManager.
 Its purpose is to minimize the work required to make observers
reflect a change in their subject. For example, if an operation
involves changes to several interdependent subjects, you might
have to ensure that their observers are notified only after all the
subjects have been modified to avoid notifying observers more
than once.

15
ChangeManager (cont.)
 ChangeManager has three responsibilities:
 It maps a subject to its observers and provides an interface to
maintain this mapping. This eliminates the need for subjects
to maintain references to their observers and vice versa.

 It defines a particular update strategy.

 It updates all dependent observers at the request of a subject.

16
subjects observers
chman

ChangeManager (cont.)

17
ChangeManager (cont.)
There are two specialized Change Managers.
 SimpleChangeManager: is naive in that it always updates all
observers of each subject.
 DAGChangeManager: handles directed-acyclic graphs of
dependencies between subjects and their observers.
 A DAGChangeManager is preferable to a SimpleChangeManager
when an observer observes more than one subject.
 The DAGChangeManager ensures the observer receives just one
update. SimpleChangeManager is fine when multiple updates aren't
an issue.

18
Related Patterns
 Mediator:
 ChangeManager is an instance of the Mediator pattern.

 Singleton:
 In general there is only one ChangeManager, and it is known
globally. The Singleton pattern would be useful here.

19

You might also like