11. Behavioral Pattern

44
BDP-1 Venkat Subramaniam Venkat Subramaniam 11. Behavioral Pattern

description

11. Behavioral Pattern. Behavioral Patters. Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects. Chain of Responsibility Pattern. - PowerPoint PPT Presentation

Transcript of 11. Behavioral Pattern

Page 1: 11. Behavioral Pattern

BDP-1Venkat SubramaniamVenkat Subramaniam

11. Behavioral Pattern

Page 2: 11. Behavioral Pattern

BDP-2Venkat SubramaniamVenkat Subramaniam

Behavioral Patters

• Concerned with algorithms & assignment of responsibilities

• Patterns of Communication between Objects

Page 3: 11. Behavioral Pattern

BDP-3Venkat SubramaniamVenkat Subramaniam

Chain of Responsibility Pattern

“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: 11. Behavioral Pattern

BDP-4Venkat SubramaniamVenkat Subramaniam

Example that would benefit from Chain Of Responsibility Pattern• Various types of Controls are used in an

application. Controls handle certain events while they do not handle others. Each control may be invoked from other controls. An event not handled by a control must be passed on to its parent control.

Page 5: 11. Behavioral Pattern

BDP-5Venkat SubramaniamVenkat Subramaniam

Example usingChain of Responsibility Pattern

Event Handler

handleEvent()

Control1

handleEvent()

Control2

handleEvent()

Client

Page 6: 11. Behavioral Pattern

BDP-6Venkat SubramaniamVenkat Subramaniam

When to use Chain OfResponsibility Pattern

• More than one object may handle a request, and the handler isn’t known ahead of time.

• One of several objects may be the intended receiver

• Set of objects that handle request is dynamic

Page 7: 11. Behavioral Pattern

BDP-7Venkat SubramaniamVenkat Subramaniam

Consequences of using Chain Of Responsibility

• Reduced Coupling

• Flexibility in assigning responsibilities– Distributes responsibilities among objects

• Receipt isn’t guaranteed

Page 8: 11. Behavioral Pattern

BDP-8Venkat SubramaniamVenkat Subramaniam

Chain Of ResponsibilityVs. Other Patterns

• Often used with Composite– Parent acts as Successor

Page 9: 11. Behavioral Pattern

BDP-9Venkat SubramaniamVenkat Subramaniam

Iterator Pattern

“Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation”

Page 10: 11. Behavioral Pattern

BDP-10Venkat SubramaniamVenkat Subramaniam

Example that would benefit from Iterator

• Several types of collections are available– List, Set, Queue, Vector

• We are interested in performing some operation on each element in a collection, without regard to which collection we use

Page 11: 11. Behavioral Pattern

BDP-11Venkat SubramaniamVenkat Subramaniam

Example usingIterator Pattern

ClientAggregate

CreateIterator()

Iterator

First()Next()IsDone()CurrentItem()

ConcreteIteratorConcreateAggregate

Page 12: 11. Behavioral Pattern

BDP-12Venkat SubramaniamVenkat Subramaniam

When to use Iterator Pattern

• Elements of an Aggregate needs to be accessed without exposing internal representation of the aggregate

• multiple traversals on an aggregate

• uniform traversal on different aggregates

Page 13: 11. Behavioral Pattern

BDP-13Venkat SubramaniamVenkat Subramaniam

Consequences of using Iterator

• Supports variations in the traversal

• Simplifies interface of Aggregates

• More than one traversal may be acting on the aggregate at any time

Page 14: 11. Behavioral Pattern

BDP-14Venkat SubramaniamVenkat Subramaniam

IteratorVs. Other Patterns

• Often applied to recursive structures such as Composite

• Factory method instantiate appropriate Iterator

• Memento used in conjunction with Iterator. Iterator stores memento internally to capture the state

Page 15: 11. Behavioral Pattern

BDP-15Venkat SubramaniamVenkat Subramaniam

Mediator Pattern

“Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently”

Page 16: 11. Behavioral Pattern

BDP-16Venkat SubramaniamVenkat Subramaniam

Example that would benefit from Mediator

• An application is used to design Wheels• The diameter of the rim is restricted by

the Hub diameter• The tire diameter is dependent on the rim• The spokes length needs to be altered if

hub diameter or rim diameter is changed

Page 17: 11. Behavioral Pattern

BDP-17Venkat SubramaniamVenkat Subramaniam

Example usingMediator Pattern

Hub

Rim

Spoke

Tire

Mediator

Page 18: 11. Behavioral Pattern

BDP-18Venkat SubramaniamVenkat Subramaniam

When to use Mediator Pattern

• Set of objects communicate in complex well defined way

• You want to reduce interdependency between objects

• Reusing object is difficult if it refers to several other objects

• Behavior distributed between several classes must be customizable without lot of sub-classing

Page 19: 11. Behavioral Pattern

BDP-19Venkat SubramaniamVenkat Subramaniam

Consequences of using Mediator

• Localizes behavior that may otherwise be distributed among several objects

• Subclass mediator to change this behavior

• Decouples Colleagues

• Replaces many-to-many interactions with one-to-many interaction– Easy to maintain, extend and understand

Page 20: 11. Behavioral Pattern

BDP-20Venkat SubramaniamVenkat Subramaniam

Mediator Vs. Other Patterns

• Facade– In Mediator, Colleague objects know Mediator– In Facade subsystem classes do not see Facade

• Colleagues may communicate with Mediator using Observer

Page 21: 11. Behavioral Pattern

BDP-21Venkat SubramaniamVenkat Subramaniam

Memento Pattern

“Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to its state later”

Page 22: 11. Behavioral Pattern

BDP-22Venkat SubramaniamVenkat Subramaniam

Example that would benefitfrom Memento

• You want to let the user modify an object

• However the user may cancel the modification

• You want to store the internal state of a complex object to restore it later

Page 23: 11. Behavioral Pattern

BDP-23Venkat SubramaniamVenkat Subramaniam

Example using Memento Pattern

OriginatorstateSetMemento(Memento m)CreateMemento()

Mementostate GetState()SetState()

Caretaker

state = m->GetState()return new Memento(state)

Page 24: 11. Behavioral Pattern

BDP-24Venkat SubramaniamVenkat Subramaniam

When to use Memento Pattern

• A snapshot of an object’s state must be saved to restore later

• you do not want to expose the implementation details of the internal state of an object, breaking its encapsulation

Page 25: 11. Behavioral Pattern

BDP-25Venkat SubramaniamVenkat Subramaniam

Consequences of using Memento

• Simplifies the Originator• Preserves encapsulation boundaries• May be expensive• Defining narrow and wide interfaces

– How to ensure only originator accesses memento’s state

• Caretaker is responsible for deleting memento– Lightweight caretakers may be burdened with large

mementos

Page 26: 11. Behavioral Pattern

BDP-26Venkat SubramaniamVenkat Subramaniam

Memento Vs. Other Patterns

• Command– May use mementos to maintain state for undo operations

• Iterator– Mementos can be used for storing internal state of iterators

Page 27: 11. Behavioral Pattern

BDP-27Venkat SubramaniamVenkat Subramaniam

Observer Pattern

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

Page 28: 11. Behavioral Pattern

BDP-28Venkat SubramaniamVenkat Subramaniam

Example that would benefit from Observer

• You have several views of a document– Graph View– TabularView– ChartView

• The user may change the data of a document from any of the visible views

• You want to keep all the views synched with the change to the document’s data

Page 29: 11. Behavioral Pattern

BDP-29Venkat SubramaniamVenkat Subramaniam

Example using Observer Pattern

Abstract Document

Attach(View observerView)Detach(View observerView)Notify()

View

Update

Observers

GraphView TabularView ChartViewYourDocument

Page 30: 11. Behavioral Pattern

BDP-30Venkat SubramaniamVenkat Subramaniam

When to use Observer Pattern• When an abstraction has two aspects one dependent

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

• Change to one object requires change to others– don’t know how many objects need change

• Object is able to notify other objects without knowing who these objects are - don’t want tight coupling

Page 31: 11. Behavioral Pattern

BDP-31Venkat SubramaniamVenkat Subramaniam

Consequences of using Observer

• Abstract the coupling between observers and subject

• Support for broadcast communication• Unexpected updates

– May be expensive and untimely• May abstract a hint on the subject change

Page 32: 11. Behavioral Pattern

BDP-32Venkat SubramaniamVenkat Subramaniam

Observer Vs. Other Patterns

• Mediator may be used to mediate between several subjects and observers

Page 33: 11. Behavioral Pattern

BDP-33Venkat SubramaniamVenkat Subramaniam

State Pattern

“Allow an object to alter its behavior when its internal state changes. The object will appear to change its state”

Page 34: 11. Behavioral Pattern

BDP-34Venkat SubramaniamVenkat Subramaniam

Example that would benefit from State Pattern

• A train may run in forward or reverse mode.

• When running in forward mode the head lights on the front engine are on and the tail lights on the back engine are on.

• When running in reverse mode the reverse is true.

• Acceleration will move the engine forward or backward depending on the mode

Page 35: 11. Behavioral Pattern

BDP-35Venkat SubramaniamVenkat Subramaniam

Example using State Pattern

Train

turnHeadLights()turnTailLights()accelerate()

TrainDirectioncurrentMode

ForwardMode

turnHeadLights()turnTailLights()accelerate()

ReverseMode

turnHeadLights()turnTailLights()accelerate()

Page 36: 11. Behavioral Pattern

BDP-36Venkat SubramaniamVenkat Subramaniam

When to use State Pattern

• An object’s behavior depends on its state and must change its behavior at run-time depending on that state

• Operations have large conditional statements that depend on the state. State pattern puts each branch of the conditional in a separate class.

Page 37: 11. Behavioral Pattern

BDP-37Venkat SubramaniamVenkat Subramaniam

Consequences of using State

• Localizes state-specific behavior and partitions behavior for different states

• Makes state transitions explicit

• State objects can be shared

Page 38: 11. Behavioral Pattern

BDP-38Venkat SubramaniamVenkat Subramaniam

State Vs. Other Patterns

• Flyweight pattern may be used to share state which may be singletons.

Page 39: 11. Behavioral Pattern

BDP-39Venkat SubramaniamVenkat Subramaniam

Strategy Pattern

“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it”

Page 40: 11. Behavioral Pattern

BDP-40Venkat SubramaniamVenkat Subramaniam

Example that would benefit fromStrategy Pattern• A property may be computed using one of

several methods/algorithms• Each method comes with its own features and

trade-offs– For instance, a method may converge towards a

result at a faster rate but may use more memory– Another method may not require as much memory

• Design your class such that the client may use any applicable method to compute property

Page 41: 11. Behavioral Pattern

BDP-41Venkat SubramaniamVenkat Subramaniam

Example using Strategy Pattern

Property

Compute()

MethodForProperty

compute()

Method1

compute()

Method1

compute()

methodToUse

Page 42: 11. Behavioral Pattern

BDP-42Venkat SubramaniamVenkat Subramaniam

When to use Strategy Pattern• Many related classes differ only in their behavior.

Strategy provides a way to configure a class with one of many behaviors

• Use different variants of an algorithm

• Algorithm uses data that clients shouldn’t know about. Strategy avoids exposing complex algorithm-specific data structures

• class defines many behaviors and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own strategy class.

Page 43: 11. Behavioral Pattern

BDP-43Venkat SubramaniamVenkat Subramaniam

Consequences of using Strategy

• Families of related algorithms• Alternative to subclassing• Strategies eliminate conditional statements• Choice of implementations

• Clients must be aware of different strategies• Communication overhead between Strategy and

Context• Increased number of objects

Page 44: 11. Behavioral Pattern

BDP-44Venkat SubramaniamVenkat Subramaniam

Strategy Vs. Other Patterns

• Often make good Flyweights