IntroductiontoSoftwareTechnology5.DesignPatterns
KlausOstermann
EinführungindieSoftwaretechnik1
TopicsofthisLecture
EinführungindieSoftwaretechnik2
} DesignPatterns} Template} Strategy} Bridge} Decorator
} ThesedesignpatternsarelessgeneralthantheGRASPpatterns} Theyfocusonspecificdesignproblems
} ThesearesomeofthemostcommonandmostimportantclassicaldesignpatternsinOOdesign
TemplateMethodPattern
EinführungindieSoftwaretechnik3
} Thegoalistoseparate...} policiesfromdetailedmechanisms.} invariantandvariantparts.
} Abstractclasses...} defineinterfaces.} implementhigh-levelpolicies.
} Controlsub-classextensions.} Avoidcodeduplication.} TheTemplateMethodPatternisatthecoreofthedesignofobject-orientedframeworks.
Using the Template Method Pattern for Bubble-Sort
EinführungindieSoftwaretechnik4
public abstract class BubbleSorter{ protected int length = 0; protected void sort() { if(length <= 1) return; for(int nextToLast= length-2; nextToLast>= 0; nextToLast--) for(int index = 0; index <= nextToLast; index++) if(outOfOrder(index)) swap(index); } protected abstract void swap(int index); protected abstract boolean outOfOrder(int index);
}
IntBubbleSorter
EinführungindieSoftwaretechnik5
public class IntBubbleSorter extends BubbleSorter{ private int[] array = null; public void sort(int[] theArray) { array = theArray; length = array.length; super.sort(); } protected void swap(int index) { int temp = array[index]; array[index] = array[index+ 1]; array[index+1] = temp; } protected boolean outOfOrder(int index) { return(array[index] > array[index+ 1]); }
}
Discussion
EinführungindieSoftwaretechnik6
Discussion
EinführungindieSoftwaretechnik7
} Templatemethodforcesdetailedimplementationstoextendthetemplateclass.
} Detailedimplementationdependonthetemplate.} Cannotre-usedetailedimplementations‘functionality.(E.g.,swapandout-of-orderaregenerallyuseful.)
} Ifwewanttore-usethehandlingofintegerarrayswithothersortingstrategieswemustremovethedependency} thisleadsustotheStrategyPattern.
StrategyPattern
EinführungindieSoftwaretechnik8
} Intent} Defineafamilyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Strategyletsthealgorithmvaryindependentlyfromclientsthatuseit.
} ComparisonWithTemplate} Usingthestrategypattern,both-thetemplateandthedetailedimplementations-dependonabstractions.
} BasicStructure
StrategyPattern:Example
EinführungindieSoftwaretechnik9
Strategy:GeneralStructure
EinführungindieSoftwaretechnik10
Defineafamilyofalgorithms,encapsulateeachone,andmaketheminterchangeable
StrategyPattern:Discussion
EinführungindieSoftwaretechnik11
} Useifmanyrelatedclassesdifferonlyintheirbehaviorratherthanimplementingdifferentrelatedabstractions.} Strategiesallowtoconfigureaclasswithoneofmanybehaviors.
} Useifyouneeddifferentvariantsofanalgorithm.} Strategiescanbeusedwhenvariantsofalgorithmsareimplementedasaclasshierarchy.
} Useifaclassdefinesmanybehaviorsthatappearasmultipleconditionalstatementsinitsoperations.} Moverelatedconditionalbranchesintoastrategy
StrategyvsSubclassing
EinführungindieSoftwaretechnik12
} Sub-classingContextmixesalgorithm‘simplementationwiththatofContext.Contexthardertounderstand,maintain,extend.
} Whenusingsub-classingwecan'tvarythealgorithmdynamically.
} Sub-classingresultsinmanyrelatedclasses.Onlydifferinthealgorithmorbehaviortheyemploy.
} EncapsulatingthealgorithminStrategy...} letsyouvarythealgorithmindependentlyofitscontext.} makesiteasiertoswitch,understand,andextendthealgorithm.
PassingContextInformationtoStrategy
EinführungindieSoftwaretechnik13
} TheStrategyinterfaceissharedbyallconcreteStrategyclasseswhetherthealgorithmstheyimplementaretrivialorcomplex.
} Someconcretestrategieswon'tusealltheinformationpassedtothem} Simpleconcretestrategiesmayusenoneofit.} Contextcreates/initializesparametersthatnevergetused.
} IfthisisanissueuseatightercouplingbetweenStrategyandContext;letStrategyknowaboutContext
PassingContextInformationtoStrategy
EinführungindieSoftwaretechnik14
} Twopossiblestrategies:} Passtheneededinformationasaparameter.
} ContextandStrategydecoupled} Communicationoverhead} Algorithmcan’tbeadaptedtospecificneedsofcontext
} ContextpassesitselfasaparameterorStrategyhasareferencetoitsContext.} Reducedcommunicationoverhead} Contextmustdefineamoreelaborateinterfacetoitsdata} ClosercouplingofStrategyandContext.} Avoidclosercouplingbydefininganexplicitinterfaceforretrievingcontext,whichisimplementedbythecontext
BridgePattern:Motivation
EinführungindieSoftwaretechnik15
Wewanttosupportmultipleoperatingsystems...
Wewanttoprovidedifferenttypesofwindows...
BridgePattern
EinführungindieSoftwaretechnik16
} Whichalternativewouldbebetterrepresentedusinginheritance?
} Whattechniquecanweusetoprovidebothtypesofclassifications?
BridgePattern
EinführungindieSoftwaretechnik17
} Intent} Decoupleanabstractionfromitsimplementationsothatthetwocanvaryindependently.
} Structure
BridgePattern:Example
EinführungindieSoftwaretechnik18
} Byencapsulatingtheconceptthatvarieswecanavoidproblemswithinheritanceconflicts.
} ThisisverysimilartothetechniqueusedintheStrategypattern
BridgePattern:Discussion
EinführungindieSoftwaretechnik19
} Decouplinginterfaceandimplementation:} Implementationcanbeconfiguredatrun-time.} Implementationbeingusedishiddeninsideabstraction.
} ImprovedextensibilityAbstractionandImplementerhierarchiescanbeextendedindependently.
} Issues} Mostlanguagesdonotsupportparallelhierarchiesverywell
} Typesafetyproblems
DecoratorPattern
EinführungindieSoftwaretechnik20
} Intent} Weneedtoaddresponsibilitiestoexistingindividualobjects} …dynamicallyandtransparently,withoutaffectingotherobjects.} …responsibilitiescanbewithdrawndynamically.
} Problem:Extensionbysubclassingisnotpractical:} Largenumberofindependentextensionsarepossible.} Wouldproduceanexplosionofsubclassestosupportevery
combination.} Nosupportfordynamicadaptation.} Aclassdefinitionmaybehiddenorotherwiseunavailablefor
subclassing} Cannotchangeallconstructorcallstotheclasswhoseobjectareto
beextended
LimitationsofInheritance:Example
EinführungindieSoftwaretechnik21
Evolution:AddingfunctionalitytoaByteArrayInputStreamtoreadwholesentencesandnotjustsinglebytes.
LimitationsofInheritance:Example
EinführungindieSoftwaretechnik22
Evolution:WealsowanttohavethepossibilitytoreadwholesentencesusingFileInputStreams...
Afterthen-thiteration…
EinführungindieSoftwaretechnik23
} Problems:} …anewclassforeachresponsibility.} responsibilitymixfixedstatically.
(HowaboutPipedDataBufferedInputStream?)} non-reusableextensions;codeduplication;} maintenancenightmare:exponentialgrowthofnumberofclasses
MultipleInheritanceisnoSolutionEither
EinführungindieSoftwaretechnik24
} staticresponsibilitymix} namingconflicts} hardtodispatchsupercallscorrectly
“Multipleinheritanceisgood,butthereisnogoodwaytodoit.”
A.SYNDER
StructureoftheDecoratorPattern
EinführungindieSoftwaretechnik25
Intent:Weneedtoaddresponsibilitiestoexistingindividualobjectsdynamicallyandtransparently,withoutaffectingotherobjects.
Example:Decoratorinjava.io
EinführungindieSoftwaretechnik26
} java.ioabstractsvariousdatasourcesanddestinations,aswellasprocessingalgorithms:} Programsoperateonstreamobjects...} independentlyofultimatedatasource/destination/shapeofdata.
DecoratorPattern:Discussion
EinführungindieSoftwaretechnik27
} Decoratorenablesmoreflexibilitythaninheritance:} Responsibilitiescanbeadded/removedatrun-time.} DifferentDecoratorclassesforaspecificComponentclassenabletomixandmatchresponsibilities.
} Easytoaddaresponsibilitytwice;e.g.,foradoubleborder,attachtwoBorderDecorators
} Decoratoravoidsincoherentclasses:} feature-ladenclasseshighupinthehierarchypay-as-you-goapproach:don'tbloat,butextendusingfine-grainedDecoratorclasses} functionalitycanbecomposedfromsimplepieces.} anapplicationdoesnotneedtopayforfeaturesitdoesn'tuse.
Decorator:Problems
EinführungindieSoftwaretechnik28
} Lotsoflittleobjects} AdesignthatusesDecoratoroftenresultsinsystemscomposedoflotsoflittleobjectsthatalllookalike.
} Objectsdifferonlyinthewaytheyareinterconnected,notintheirclassorinthevalueoftheirvariables.Imagineaclasstodrawaborderaroundacomponent..
} Suchsystemsareeasytocustomizebythosewhounderstandthem,butcanbehardtolearnanddebug.
} Objectidentity} Adecoratoranditscomponentaren'tidentical.Fromanobjectidentitypointofview,adecoratedcomponentisnotidenticaltothecomponentitself.
} Youshouldn'trelyonobjectidentitywhenyouusedecorators
Example:Streamsinjava.io
EinführungindieSoftwaretechnik29
} AstreamisnormallyaddressedviatheoutermostDecorator.} Sometimes,areferencetooneoftheinternalobjectsismaintainedandoperatedon} operationshouldn’tincludeactualreadsorwrites} goodstyle:allread()operationsareperformedonlytothehead
decoratorinthecompositestreamobject
} Readingfromaninternalobjectbreakstheillusionofasingleobjectaccessedviaasinglereference,andmakesthecodemoredifficulttounderstand.
FileInputStream fin = new FileInputStream(“a.txt”); BufferedInputStream din = new BufferedInputStream(fin); fin.read();
Decorator:Problems
EinführungindieSoftwaretechnik30
} Nolatebinding} DELEGATIONVERSUSFORWARDSEMANTICS
Forwardingwithbindingofthistomethodholder;"ask"anobjecttodosomethingonitsown.
Bindingofthistomessagereceiver:“ask”anobjecttodosomethingonbehalfofthemessagereceiver.
NoLateBinding:Example
EinführungindieSoftwaretechnik31
Decorator:Problems
EinführungindieSoftwaretechnik32
} Needtoimplementforwardingmethodsforthosemethodsnotrelevanttothedecorator} Alotofrepetitiveprogrammingwork} Amaintenanceproblem:Whatifthedecoratedclasschanges
} Addingnewmethodsorremovingmethodsthatareirrelevanttothedecorators
} Decoratorclassesneedtochangeaswell} Thisisavariantoftheso-called“fragilebaseclassproblem”
Decorator:Issues
EinführungindieSoftwaretechnik33
} Keepthecommonclass(Component)lightweight:} itshouldfocusondefininganinterface(e.g.implementedasinterface).
} deferdefiningdatarepresentationtosubclasses.} otherwisethecomplexityofComponentmightmakethedecoratorstooheavyweighttouseinquantity.
} PuttingalotoffunctionalityintoComponentmakesitlikelythatsubclasseswillpayforfeaturestheydon'tneed.
} Theseissuesrequirepre-planning.} Difficulttoapplydecoratorpatternto3rd-partycomponentclass.
Literature
EinführungindieSoftwaretechnik34
} A.Shalloway,J.R.Trott.DesignPatternsExplained.Addison-Wesley,2005.} Chap.9,14,15,18