designpatterns-06.pdf

Upload: kiranshingote

Post on 03-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 designPatterns-06.pdf

    1/19

    The Decorator Pattern

    CSCI 3132 Summer 20111

  • 7/29/2019 designPatterns-06.pdf

    2/19

    StarbuzzCoffee

    Wanttoofferavarietyofcombina5onsofcoffeeandcondiments

    Costofacupdependsonthecombina5onthatwasordered

    2

  • 7/29/2019 designPatterns-06.pdf

    3/19

    FirstDesign

    Makeabeverageclassandasubclassforeachlegalcombina5on

    3

    HouseBlend

    cost()

    DarkRoast

    cost()

    Decaf

    cost()

    Espressocost

    ()

    HouseBlendWithSteamedMilkcost()

    DarkRoastWithSteamedMilkcost()

    DecafWithSteamedMilkcost()

    EspressoWiSteamedMicost()HouseBlend

    Mochacost()

    DarkRoastMochacost()

    DecafMochacost()

    EspressoMochacost()HouseBlend

    WithWhip

    cost

    DarkRoastWithWhip

    DecafWithWhip

    cost

    EspressoWithWhipcost()

    BeverageString description

    getDescription() cost()

    3

  • 7/29/2019 designPatterns-06.pdf

    4/19

    ProblemswithInheritance

    Toomanysubclassesmaybeneeded. Needtodefinetheimplementa5onofeach

    subclass.

    Allclassesinheritasta5cbehaviourwhichmayhavetobeoverridden.

    Theinheritedbehaviourcannotbechangedatrun5me,i.e.behaviourissta5catrun5me.

    Thus,thedesignisnotflexibleormaintainable.

    4

  • 7/29/2019 designPatterns-06.pdf

    5/19

    SecondDesign

    Makethesuperclasscontainbooleanstospecifywhichcondimentsareincludedandsubclassesforeachtypeofcoffee

    Howdowecomputecost? Whatdoesittaketoaddanewcondiment?

    5

  • 7/29/2019 designPatterns-06.pdf

    6/19

    BeverageString descriptionmilk

    soymochawhipgetDescription()cost

    ()

    hasMilk()setMilk()hasSoy()setSoy()hasMocha()setMocha()hasWhip()setWhip()

    HouseBlend

    cost()

    DarkRoastcost()

    Decafcost()

    Espressocost()

    6

  • 7/29/2019 designPatterns-06.pdf

    7/19

    DesignPrinciple

    Classesshouldbeopenforextension,butclosedformodifica5on

    extensionisNOTsubclassing

    Itmeanstheaddi5onofnewbehavior(withoutmodifyingthecode!)

    7

  • 7/29/2019 designPatterns-06.pdf

    8/19

    DecoratorPaern

    Startwithaninstanceofthebasicclassesandthendecorateitwithnewcapabili5es

    Dark Roast

    Mocha

    cost()cost()

    Whip

    cost() 0.990.99+0.20

    0.99+0.20+0.10

    8

  • 7/29/2019 designPatterns-06.pdf

    9/19

    KeyPoints

    Decoratorshavethesamesupertypesastheobjectstheydecorate

    Thisletsuspassaroundthedecoratedobjectinsteadoftheoriginal(unwrapped)object

    Decoratoraddbehaviorbydelega5ngtotheobjectitdecoratesandthenaddingitsownbehavior

    Canadddecora5onsatany5me

    9

  • 7/29/2019 designPatterns-06.pdf

    10/19

    ClassDiagramfortheDecoratorPaern

    10

  • 7/29/2019 designPatterns-06.pdf

    11/19

    StarbuzzCoffeeExample

    11

  • 7/29/2019 designPatterns-06.pdf

    12/19

    public abstract class Beverage{!String description = Unknown;!public String getDescription() {!return description;!}!public abstract double cost();!

    }!public abstract class CondimentDecorator extends Beverage {!public abstract String getDescription();!

    public abstract double cost();!}!public class Espresso extends Beverage {!

    public Espresso() {!description = Espresso;

    !}!public double cost() {!

    return 1.99;!}!

    }! 12

  • 7/29/2019 designPatterns-06.pdf

    13/19

    public class Mocha extends CondimentDecorator {!Beverage bev;!public Mocha(Beverage bev) {!

    this.bev = bev;!}!public String getDescription {!

    return bev.getDescription() + , Mocha;!}!public double cost() {!

    return .20 + bev.cost();!}!

    }!

    13

  • 7/29/2019 designPatterns-06.pdf

    14/19

    public class StarBuzz {!public static void main(String args[]) {!

    Beverage bev = new Espresso); !bev = new Mocha(bev);!bev = new Mocha(bev);!bev = new Whip(bev);!bev = new Soy(bev);!System.out.println(bev.getDescription() + $+!

    bev.getCost()); !}!

    14

  • 7/29/2019 designPatterns-06.pdf

    15/19

    DecoratorsinJava

    FileI/OExample

    FileInputStream

    BufferedInputStream

    LineNumberInputStream

    Component

    Concrete decorators

    15

  • 7/29/2019 designPatterns-06.pdf

    16/19

    DesignPrinciplefortheDecoratorPaern

    Classesshouldbeopenforextensionbutclosedformodifica5on.

    Systemscanbeextendedwithoutchangingexis5ngcode. Tradeoffs:

    Takes5meandeffort. Introducesnewlevelsofabstrac5onwhichmakes

    designsmorecomplicatedandcodehardtounderstand.

    Duetothetradeoffsthedecoratorpaernshouldnotbeusedthroughoutthedesignbutinareasthataremostlikelytochange.

    Experienceandlookingatotherexampleshelpsonedeterminewhichareasarelikelytochange.

    16

  • 7/29/2019 designPatterns-06.pdf

    17/19

    DecoratorPaern

    Providesaflexiblealterna5vetousinginheritancetoextendfunc5onality.

    Thisachievedbyintroducingdecoratorsthatdecorateobjects. Decoratorshavethesametypeastheobjects

    theydecorate.

    Anobjectcanhaveoneormoredecorators.17

  • 7/29/2019 designPatterns-06.pdf

    18/19

    TheDecoratorPaern

    Thedecoratedobjectandtheoriginalobjecthavethesametype.Thus,thedecoratedobjectcanbepassedinsteadoftheoriginal

    object. Thedecoratordelegatespartofitsbehaviour

    totheobjectitdecorates.

    ItaddsitsownbehaviourbeforeoraZerthedelega5on.

    Objectscanbedelegateddynamicallyatrun5me.

    Theobjectsarewrappedwithdecorators.18

  • 7/29/2019 designPatterns-06.pdf

    19/19

    DecoratorPaernSummary

    Maindesignprinciple:Classesshouldbeopenforextensionbutclosedformodifica5on.

    Achievesflexibility-behaviourcanbeextendedwithoutchangingexis5ngcode.

    Composi5onanddelega5onisusedtoaddnewbehavioursatrun5me.

    Asetofdecoratorclassesareusedtowrapconcretecomponents. Overuseofdecoratorscanbecomplexastheycanintroduceanumberofsmallobjectsintoadesign.

    19