design patterns · umesh nair 11 seminar series on design patterns consequences reduced coupling....

34
Umesh Nair 1 Seminar Series on Design Patterns A seminar series on Design Patterns by Eric Gamma et al. September 11, 2006: Observer, Mediator and Chain of Responsibility Presented by: Umesh Nair

Upload: others

Post on 07-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 1 Seminar Series on Design Patterns

A seminar series on

Design Patternsby Eric Gamma et al.

September 11, 2006: Observer, Mediator and Chain of Responsibility

Presented by: Umesh Nair

Page 2: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 2 Seminar Series on Design Patterns

Today’s patterns:

• Chain of Resposibility (CoR)

• Observer

• Mediator

All of these help decoupling co-ordinating objects.

Page 3: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 3 Seminar Series on Design Patterns

(Page 223): Chain of Responsibility

Intent

Avoid coupling the sender of a request to its receiver by giving more

than one object a chance to handle the request. Chain the receiving

objects and pass the request along the chain until an object handles

it.

Page 4: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 4 Seminar Series on Design Patterns

An example

Consider a Template Method base class Speaker:

class Speaker {

public:

Speaker(Speaker* standIn = 0) : fNext(standIn) {}

void GiveTalk();

protected:

virtual bool WillingToSpeak() = 0;

virtual void DoGiveTalk() = 0;

private:

void GiveDefaultTalk() {}

Speaker* fNext;

};

void Speaker::GiveTalk() {

if (WillingToSpeak()) { DoGiveTalk(); }

else if (fNext) { fNext→GiveTalk(); }

else { GiveDefaultTalk(); }

}

Page 5: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 5 Seminar Series on Design Patterns

Now consider concrete Speaker subclasses:

WillingToSpeakDoGiveTalk

fNext

Speaker

GiveTalk

Pat

WillingToSpeakDoGiveTalk

Alex

WillingToSpeakDoGiveTalk

John

WillingToSpeakDoGiveTalk

Assume these concrete Speakers are singletons, and they’ve been

initialized in the following chain:

fNext

Alex

fNext

Pat

fNext

John

designatedSpeaker

What happens when we call designatedSpeaker->GiveTalk()?

Page 6: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 6 Seminar Series on Design Patterns

Structure (From the book):

Page 7: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 7 Seminar Series on Design Patterns

Implemented as a CoR as described

class Speaker {

public:

Speaker(Speaker* standIn = 0) : fNext(standIn) {}

void GiveTalk();

private:

void GiveDefaultTalk() {}

Speaker* fNext;

};

void Speaker::GiveTalk() {

if (fNext) { fNext→GiveTalk(); }

else { GiveDefaultTalk(); }

}

void Alex::GiveTalk() {

if (IAmPrepared()) { GiveMyTalk(); }

else { Speaker::GiveTalk(); }

}

Page 8: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 8 Seminar Series on Design Patterns

Highlights:

• The base class maintains a “next” pointer.

• Each derived class implements its contribution for handling the request.

• If the request needs to be “passed on,” then the derived class “calls

back” to the base class, which delegates the next pointer.

• The client creates and links the chain.

• The client “launches and leaves” each request with the root of the

chain.

Related patterns:

Page 9: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 9 Seminar Series on Design Patterns

Real world examples:

• A coin sorter:

• A sieve system to separate stones:

Larger stones are collected in upper sieves. Smaller stones get filtered

to lower sieves.

Page 10: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 10 Seminar Series on Design Patterns

Computer science examples:

• Exception handling in Languages like C++ , Java etc.

• Function scoping in many languages.

• GUI help sustems.

• GUI event handling.

Cases where this pattern is used:

• AWT 1.0 Graphics library in Java.

• EventHandler in MacApp and ET++.

• Beurocrat in THINK Class Library (Symantec).

• Responder in NeXT’s AppKit.

• Tk uses it to process an image.

Page 11: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 11 Seminar Series on Design Patterns

Consequences

• Reduced coupling.

• Added flexibility in assigning responsibilities to objects.

• Receipt isn’t guaranteed.

• Not good to find the best receiver.

The main pitfall of this pattern is inefficiency. In the case of a help system

or GUI event handling, traversing a sequential chain of objects is often

inefficient, and here comes our next pattern-Observer.

Page 12: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 12 Seminar Series on Design Patterns

(Page 293): Observer

Also Known As:

• Publish/Subscribe

• Dependents

Intent

Define a one-to-many dependency between objects so that when one

object changes state, all its dependents are notified and updated

automatically.

Page 13: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 13 Seminar Series on Design Patterns

Problem: Data management and Revision control

• Data management library

– All objects are derived from an object Object.

– Concurrent editing of an object is prevented by a locking mechanism

down in this library. A function Object::lock() is called before an

object needs to be edited, and if it is not possible, editing is

prevented.

• Applications

– A Revision control system is implemented in an application, that

needs checking out the object from a repository before editing.

– This is complex when there are dependencies between objects.

– Logic for checking out these dependent objects should be in the

application.

• Solution: Do the checkout in Object::lock().

Page 14: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 14 Seminar Series on Design Patterns

Solution 1: Let Object::lock() call the revision control API.

Problems:

• It may be difficult to refactor the revision control API from the

Application.

• Different applications may use different RC systems that do not share a

common API.

• In 95% cases, RC is not used, so calling a RC API in those cases may

be inefficient.

Solution 2: Let Object::lock() provide a mechanism so thatclients can register the actions, which will be called when thelocking happens.

Advantages:

• RC implementation can be in individual applications, and can be

different.

• No additional functions are called if there is no RC.

This is essentially a callback mechanism.

Page 15: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 15 Seminar Series on Design Patterns

Callback mechanism

• Callback mechanism is not really an object-oriented technique. In C,

this is achieved by function pointers.

typedef bool (*CallbackFunc)(obj);

void register(CallbackFunc func);

for i=0; i<n; ++i) {

funcs[i](obj);

. . .

}

• In C++ , this can be achieved by providing an interface class. The

clients can inherit it and override the handling function.

This is the Observer pattern.

Page 16: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 16 Seminar Series on Design Patterns

Structure (From the book):

Page 17: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 17 Seminar Series on Design Patterns

Structure and Participants

• Subject

– Knows its observers. Any number of Observer objects may observe a

subject.

– Provides an interface for attaching and detaching Observer objects.

• Observer

– Defines an updating interface for objects that should be notified of

changes in a subject

• ConcreteSubject

– Stores state of interest to ConcreteObserver objects.

– Sends a notification to its observers when its state changes.

• ConcreteObserver

– Maintains a reference to a ConcreteSubject object.

– Stores state that should stay consistent with the subject’s.

– Implements the Observer updating interface to keep its state

consistent with the subject’s.

Page 18: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 18 Seminar Series on Design Patterns

Structure (From Wikipedia):

Page 19: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 19 Seminar Series on Design Patterns

Consequences

• Abstract coupling between Subject and Observer.

• Support for broadcast communication.

• Unexpected updates.

Page 20: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 20 Seminar Series on Design Patterns

Implementation

• Mapping subjects to their observers.

• Observing more than one subject.

• Who triggers the update? The Subject, or the Client?

• Dangling references to deleted subjects.

• Making sure Subject state is self-consistent before notification.

• Avoiding observer-specific update protocols: the push and pull models.

• Specifying modifications of interest explicitly.

Page 21: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 21 Seminar Series on Design Patterns

An example: Document view system

• The same data (subject) is represented in three views

(observers)-spreadsheet, bar chart and pie chart.

• Whenever any data changes, that is notified to the views (observers).

Page 22: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 22 Seminar Series on Design Patterns

A real life example: An auction system

• The auctioner is the subject, who changes the data (the bid price)

based on the auctions.

• The Bidders are the Observers, who are notified when the data changes.

• A mediator, our next pattern is similar.

Page 23: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 23 Seminar Series on Design Patterns

Known uses

• Event driven programming

– Qt Signal/Slot model

– Java Swing library

– Boost signals

• As part of the Mediator pattern

• Mailing Lists/ yahoo groups

Page 24: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 24 Seminar Series on Design Patterns

(Page 273): Mediator

Intent

Define an object that encapsulates a set of objects interact.

Mediator promotes loose coupling by keeping objects from referring

to each other explicitely, and it lets you vary their implementations

independently.

Page 25: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 25 Seminar Series on Design Patterns

Problem: Co-ordination of airplanes

• Consider several airplanes that can control themselves while flying, but

need to co-ordinate with other airplanes when they land and take-off at

an airport

• Every plane communicating with every other plane will create a mess.

Page 26: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 26 Seminar Series on Design Patterns

Solution: Air Traffic Controllers

• Airplanes do not communicate with one another. Instead, they

communicate with the Control tower.

• Control tower does not know anything about airplanes, except the

details when they need to land and take-off.

• Control tower only handles a small function of the airplanes with

minumum coupling.

Page 27: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 27 Seminar Series on Design Patterns

Applicability:

Use the Mediator pattern when

• a set of objects communicate in well-defined but complex ways. The

resulting interdependencies are unstructured and difficult to

understand.

• reusing an object is difficult because it refers to and communicates with

many other objects.

• a behavior that’s distributed between several classes should be

customizable without a lot of subclassing.

Page 28: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 28 Seminar Series on Design Patterns

Structure (From the book):

Page 29: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 29 Seminar Series on Design Patterns

Participants:

• Mediator

– defines an interface for communicating with Colleague objects.

• ConcreteMediator

– implements cooperative behavior by coordinating Colleague objects.

– knows and maintains its colleagues.

• Colleague classes

– each Colleague class knows its Mediator object

– each colleague communicates with its mediator whenever it would

have otherwise communicated with another colleague.

Page 30: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 30 Seminar Series on Design Patterns

Consequences:

• It limits subclassing.

• It decouples colleagues.

• It simplifies object protocols.

• It abstracts how objects cooperate.

• It centralizes control.

Page 31: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 31 Seminar Series on Design Patterns

Implementation

• Omitting the abstract Mediator class.

• Colleague-Mediator communication: use Observer?

Page 32: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 32 Seminar Series on Design Patterns

Known uses

• Several GUI systems: FormsVBT, ET++, and THINK C.

• Zeus algorithm animation system (Views and Algorithms communicate

through the animation system).

• Multi-view editors.

Page 33: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 33 Seminar Series on Design Patterns

References

• The GoF book

• The Wikipedia

• http://home.earthlink.net/~houston2/dp/

Page 34: Design Patterns · Umesh Nair 11 Seminar Series on Design Patterns Consequences Reduced coupling. Added exibility in assigning responsibilities to objects. Receipt isn’t guaranteed

Umesh Nair 34 Seminar Series on Design Patterns

Thanks for listening!

See you next time!