designpatterns-10.pdf

Upload: kiranshingote

Post on 03-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 designPatterns-10.pdf

    1/23

    Chain of Responsibility

    andComposite

    CSCI 3132 Summer 2011 1

  • 7/29/2019 designPatterns-10.pdf

    2/23

    Mo#va#on

    Consideracontext-sensi#vehelpsystemforaGUIDE Theobjectthatul#matelyprovidesthehelpisn'tknownexplicitlytotheobject(e.g.,abuHon)thatini#atesthehelprequest.

    Souseachainofobjectstodecouplethesendersfromthereceivers.

    Therequestgetspassedalongthechainun#loneoftheobjectshandlesit.

    Eachobjectonthechainsharesacommoninterfaceforhandlingrequestsandforaccessingitssuccessoronthechain

    2

  • 7/29/2019 designPatterns-10.pdf

    3/23

    ChainofResponsibilityPaHern

    IntentAvoidcouplingsenderofrequesttoitsreceiverby

    givingmorethanoneobjectchancetohandle

    request.Chainreceivingobjectsandpassrequest

    alongun#lanobjecthandlesit.

    3

  • 7/29/2019 designPatterns-10.pdf

    4/23

    Example2

    4

  • 7/29/2019 designPatterns-10.pdf

    5/23

    Applicability

    UseChainofresponsibilitypaHernwhenmorethanoneobjectmayhandlearequest,and

    thehandlerisntknownapriori.

    youwanttoissuearequesttooneofseveralobjectswithoutspecifyingthereceiverexplicitly

    thesetofobjectsthatcanhandlearequestshouldbespecifieddynamically

    5

  • 7/29/2019 designPatterns-10.pdf

    6/23

    ChainofResponsibilityStructure

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

    than one object a chance to handle the request 6

  • 7/29/2019 designPatterns-10.pdf

    7/23

    Chainofresponsibility-Par#cipants

    andler(elpandler)definesaninterfaceforhandlingrequests (op#onal)implementsthesuccessorlink

    Concreteandler(PrintBuHon,PrintDialog)handlesrequestsitisresponsibleforcanaccessitssuccessor iftheConcreteHandlercanhandletherequest,is

    doesso;otherwiseitforwardstherequesttoits

    successor Client ini#atestherequesttoaConcreteHandlerobjecton

    thechain

    7

  • 7/29/2019 designPatterns-10.pdf

    8/23

    ChainofresponsibilityConsequences

    Reducedcoupling ThepaHernfreesanobjectfromknowingotherobject

    handlesarequest

    Addedflexibilityinassigningresponsibili#estoobjects changingthechaininrun-#me usesub-classingtospecifyhandlerssta#cally

    Receiptisntguaranteed

    8

  • 7/29/2019 designPatterns-10.pdf

    9/23

    ChainofresponsibilityImplementa#on

    Implemen#ngthesuccessorchaindefineanewlinks(inandlerusually),oruseexistentlinks(forexample,child-parentlinks).

    Connec#ngsuccessorsclass HelpHandler {

    public:

    HelpHandler(HelpHandler* s) : _successor(s) {}

    virtualvoid HandleHelp();

    private:

    HelpHandler* _successor;};

    void HelpHandler::HandleHelp() {

    if (_successor)

    _successor->HandleHelp();

    }

    9

  • 7/29/2019 designPatterns-10.pdf

    10/23

    ChainofresponsibilityImplementa#on

    Represen#ngrequestsThesimplestform:therequestisahard-coded

    opera#oninvoca#on

    youcanforwardonlythefixedsetofrequestsAnalterna#ve:useasinglehandlerfunc#on

    whichtakesarequestobjectasparameter

    void Handler::HandleRequest(Request* theRequest) {

    switch (theRequest->getKind()) {case Help:

    HandleHelp((HelpRequest*)theRequest);

    break;

    }

    10

  • 7/29/2019 designPatterns-10.pdf

    11/23

    BehavioralPaHernSummary

    BehavioralpaHernsareconcernedwiththeassignmentofresponsibili#esbetweenobjects,or,encapsula#ng

    behaviorinanobjectanddelega#ngrequeststoit.

    Chainofresponsibility,Command,andObserver,addresshowyoucandecouplesendersandreceivers,butwithdifferenttrade-offs.

    Chainofresponsibilitypassesasenderrequestalongachainofpoten#alreceivers.

    Commandnormallyspecifiesasender-receiverconnec#onwithasubclass.

    Observerdefinesaverydecoupledinterfacethatallowsformul#plereceiverstobeconfiguredatrun-#me.

    11

  • 7/29/2019 designPatterns-10.pdf

    12/23

    StructuralPaHerns

    Concernedwithhowclassesandobjectsarecombinedtocreatelargerstructures.

    Concernedwithcomposingobjectstoestablishnewfunc#onality.

    12

  • 7/29/2019 designPatterns-10.pdf

    13/23

    CompositePaHern

    A composite is a group of objects in which some objectscontain others; one object may represent groups, andanother may represent an individual item, a leaf.

    Facilitates the composition of objects into a stree structure,a hierarchy, that represent part-whole hierarchies.

    These hierarchies consist of both primitive and compositeobjects.

    The operations are appropriate for processing andtraversing trees.

    13

  • 7/29/2019 designPatterns-10.pdf

    14/23

    Example

    Example:complexgraphicapplica#on,withhierarchicallynestedobjects.

    Mainidea:Containersandleafobjectsappearthesametoclients. Upanddowndelega6on:

    Acontainermaydelegatetoallcontainedobjects. Aleaf/containermaydelegatetocontainingobjects.

    aLeaf aLeaf aLeaf

    aComposite

    aLeaf aLeaf

    aComposite

    14

  • 7/29/2019 designPatterns-10.pdf

    15/23

    Line

    Draw()

    Rectangle

    Draw()

    Text

    Draw()forallgingraphics

    g.Draw()

    addgtolistofgraphics

    graphics

    Picture

    Draw()

    Add(Graphicg)

    Remove(Graphic)

    GetChild(int)

    Graphic

    Draw()

    Add(Graphic)

    Remove(Graphic)

    GetChild(int)

    15

  • 7/29/2019 designPatterns-10.pdf

    16/23

    Par#cipants

    Component(Graphic) declaresinterfaceforobjectsinthecomposi#on implementsdefaultbehavior declaresaninterfaceforaccessingandmanagingitschildcomponents (op#onal)declaresaninterfaceforaccessingacomponentsparent

    Leaf(Rectangle,Line,Textetc.) definesbehaviorforprimi#veobjectsinthecomposi#on

    Composite(Picture) definesbehaviorforcomponentshavingchildren

    storeschildcomponents

    implementschild-relatedopera#onsintheComponentinterface Client

    manipulatesobjectsinthecomposi#onthroughtheComponentinterface

    16

  • 7/29/2019 designPatterns-10.pdf

    17/23

    CompositepaHern-implementa#on

    ExplicitparentreferencesdefinetheparentreferenceintheComponentclassessen#altomaintaintheinvariantthatallchildrenof

    acompositehaveastheirparentthecompositethat

    inturnhasthemaschildreneasiestwaytoensure-changethecomponents

    parentonlywhenitsbeingaddedorremovedfromcomposite

    Sharingcomponents

    mul#pleparentsambigui#esasarequestpropagatesupthestructure

    17

  • 7/29/2019 designPatterns-10.pdf

    18/23

    CompositePaHernClassDiagram

    Component

    operation()

    Leaf

    operation()

    Composite

    operation()

    other()

    *Client

    Each node of the Component structure can respond to some commonoperation(s). I.e. the client can send the common operation to Componentand the structure responds appropriately.

    18

  • 7/29/2019 designPatterns-10.pdf

    19/23

    Example

    MenuComponent

    add()

    remove()getChild()

    print()

    MenuItem

    print()

    Menu

    add()remove()getChild()

    print()

    *Waitress

    19

  • 7/29/2019 designPatterns-10.pdf

    20/23

    CompositePaHern

    Menu

    menuComponents: ArrayList

    add()

    remove()getChild()

    print()

    Note the association from Menu to MenuComponentswith an array list data type.

    How to implementation of print() in Menu and inMenuItem

    20

  • 7/29/2019 designPatterns-10.pdf

    21/23

    CompositePaHern

    In the Menu class we have a print() that is appropriate foran internal node.

    public void print() {System.out.print("\n" + getName());System.out.println(", " + getDescription());

    System.out.println("---------------------");

    Iterator iterator = menuComponents.iterator();while (iterator.hasNext()) {

    MenuComponent menuComponent =(MenuComponent)iterator.next();

    menuComponent.print();}

    }

    21

  • 7/29/2019 designPatterns-10.pdf

    22/23

    CompositePaHern

    In the MenuItem class we have a print() that is appropriatefor a leaf:

    public void print() {

    System.out.print(" " + getName());

    if (isVegetarian()) {System.out.print("(v)");}System.out.println(", " + getPrice());

    System.out.println(" -- " + getDescription());}

    22

  • 7/29/2019 designPatterns-10.pdf

    23/23

    Summary

    TheCompositePaHernisusedtorepresentpart-wholeobjecthierarchies.

    Clientsinteractwithobjectsthroughthecomponentclass.

    Itenablesclientstotoignorethespecificsofwhichleaforcompositeclasstheyuse.

    Canbeusedrecursively,sothatDisplaycanshowbothflaresandstars.

    Newcomponentscaneasilybeaddedtoadesign.

    23