introduction to software technology 5. design...

34
Introduction to Software Technology 5. Design Patterns Klaus Ostermann Einführung in die Softwaretechnik 1

Upload: others

Post on 23-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

IntroductiontoSoftwareTechnology5.DesignPatterns

KlausOstermann

EinführungindieSoftwaretechnik1

Page 2: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

TopicsofthisLecture

EinführungindieSoftwaretechnik2

}  DesignPatterns}  Template}  Strategy}  Bridge}  Decorator

}  ThesedesignpatternsarelessgeneralthantheGRASPpatterns}  Theyfocusonspecificdesignproblems

}  ThesearesomeofthemostcommonandmostimportantclassicaldesignpatternsinOOdesign

Page 3: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

TemplateMethodPattern

EinführungindieSoftwaretechnik3

}  Thegoalistoseparate...}  policiesfromdetailedmechanisms.}  invariantandvariantparts.

}  Abstractclasses...}  defineinterfaces.}  implementhigh-levelpolicies.

}  Controlsub-classextensions.}  Avoidcodeduplication.}  TheTemplateMethodPatternisatthecoreofthedesignofobject-orientedframeworks.

Page 4: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

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);

}

Page 5: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

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]); }

}

Page 6: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Discussion

EinführungindieSoftwaretechnik6

Page 7: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Discussion

EinführungindieSoftwaretechnik7

}  Templatemethodforcesdetailedimplementationstoextendthetemplateclass.

}  Detailedimplementationdependonthetemplate.}  Cannotre-usedetailedimplementations‘functionality.(E.g.,swapandout-of-orderaregenerallyuseful.)

}  Ifwewanttore-usethehandlingofintegerarrayswithothersortingstrategieswemustremovethedependency}  thisleadsustotheStrategyPattern.

Page 8: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

StrategyPattern

EinführungindieSoftwaretechnik8

}  Intent}  Defineafamilyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Strategyletsthealgorithmvaryindependentlyfromclientsthatuseit.

}  ComparisonWithTemplate}  Usingthestrategypattern,both-thetemplateandthedetailedimplementations-dependonabstractions.

}  BasicStructure

Page 9: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

StrategyPattern:Example

EinführungindieSoftwaretechnik9

Page 10: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Strategy:GeneralStructure

EinführungindieSoftwaretechnik10

Defineafamilyofalgorithms,encapsulateeachone,andmaketheminterchangeable

Page 11: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

StrategyPattern:Discussion

EinführungindieSoftwaretechnik11

}  Useifmanyrelatedclassesdifferonlyintheirbehaviorratherthanimplementingdifferentrelatedabstractions.}  Strategiesallowtoconfigureaclasswithoneofmanybehaviors.

}  Useifyouneeddifferentvariantsofanalgorithm.}  Strategiescanbeusedwhenvariantsofalgorithmsareimplementedasaclasshierarchy.

}  Useifaclassdefinesmanybehaviorsthatappearasmultipleconditionalstatementsinitsoperations.}  Moverelatedconditionalbranchesintoastrategy

Page 12: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

StrategyvsSubclassing

EinführungindieSoftwaretechnik12

}  Sub-classingContextmixesalgorithm‘simplementationwiththatofContext.Contexthardertounderstand,maintain,extend.

}  Whenusingsub-classingwecan'tvarythealgorithmdynamically.

}  Sub-classingresultsinmanyrelatedclasses.Onlydifferinthealgorithmorbehaviortheyemploy.

}  EncapsulatingthealgorithminStrategy...}  letsyouvarythealgorithmindependentlyofitscontext.}  makesiteasiertoswitch,understand,andextendthealgorithm.

Page 13: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

PassingContextInformationtoStrategy

EinführungindieSoftwaretechnik13

}  TheStrategyinterfaceissharedbyallconcreteStrategyclasseswhetherthealgorithmstheyimplementaretrivialorcomplex.

}  Someconcretestrategieswon'tusealltheinformationpassedtothem}  Simpleconcretestrategiesmayusenoneofit.}  Contextcreates/initializesparametersthatnevergetused.

}  IfthisisanissueuseatightercouplingbetweenStrategyandContext;letStrategyknowaboutContext

Page 14: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

PassingContextInformationtoStrategy

EinführungindieSoftwaretechnik14

}  Twopossiblestrategies:}  Passtheneededinformationasaparameter.

}  ContextandStrategydecoupled}  Communicationoverhead}  Algorithmcan’tbeadaptedtospecificneedsofcontext

}  ContextpassesitselfasaparameterorStrategyhasareferencetoitsContext.}  Reducedcommunicationoverhead}  Contextmustdefineamoreelaborateinterfacetoitsdata}  ClosercouplingofStrategyandContext.}  Avoidclosercouplingbydefininganexplicitinterfaceforretrievingcontext,whichisimplementedbythecontext

Page 15: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

BridgePattern:Motivation

EinführungindieSoftwaretechnik15

Wewanttosupportmultipleoperatingsystems...

Wewanttoprovidedifferenttypesofwindows...

Page 16: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

BridgePattern

EinführungindieSoftwaretechnik16

}  Whichalternativewouldbebetterrepresentedusinginheritance?

}  Whattechniquecanweusetoprovidebothtypesofclassifications?

Page 17: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

BridgePattern

EinführungindieSoftwaretechnik17

}  Intent}  Decoupleanabstractionfromitsimplementationsothatthetwocanvaryindependently.

}  Structure

Page 18: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

BridgePattern:Example

EinführungindieSoftwaretechnik18

}  Byencapsulatingtheconceptthatvarieswecanavoidproblemswithinheritanceconflicts.

}  ThisisverysimilartothetechniqueusedintheStrategypattern

Page 19: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

BridgePattern:Discussion

EinführungindieSoftwaretechnik19

}  Decouplinginterfaceandimplementation:}  Implementationcanbeconfiguredatrun-time.}  Implementationbeingusedishiddeninsideabstraction.

}  ImprovedextensibilityAbstractionandImplementerhierarchiescanbeextendedindependently.

}  Issues}  Mostlanguagesdonotsupportparallelhierarchiesverywell

}  Typesafetyproblems

Page 20: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

DecoratorPattern

EinführungindieSoftwaretechnik20

}  Intent}  Weneedtoaddresponsibilitiestoexistingindividualobjects}  …dynamicallyandtransparently,withoutaffectingotherobjects.}  …responsibilitiescanbewithdrawndynamically.

}  Problem:Extensionbysubclassingisnotpractical:}  Largenumberofindependentextensionsarepossible.}  Wouldproduceanexplosionofsubclassestosupportevery

combination.}  Nosupportfordynamicadaptation.}  Aclassdefinitionmaybehiddenorotherwiseunavailablefor

subclassing}  Cannotchangeallconstructorcallstotheclasswhoseobjectareto

beextended

Page 21: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

LimitationsofInheritance:Example

EinführungindieSoftwaretechnik21

Evolution:AddingfunctionalitytoaByteArrayInputStreamtoreadwholesentencesandnotjustsinglebytes.

Page 22: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

LimitationsofInheritance:Example

EinführungindieSoftwaretechnik22

Evolution:WealsowanttohavethepossibilitytoreadwholesentencesusingFileInputStreams...

Page 23: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Afterthen-thiteration…

EinführungindieSoftwaretechnik23

}  Problems:}  …anewclassforeachresponsibility.}  responsibilitymixfixedstatically.

(HowaboutPipedDataBufferedInputStream?)}  non-reusableextensions;codeduplication;}  maintenancenightmare:exponentialgrowthofnumberofclasses

Page 24: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

MultipleInheritanceisnoSolutionEither

EinführungindieSoftwaretechnik24

}  staticresponsibilitymix}  namingconflicts}  hardtodispatchsupercallscorrectly

“Multipleinheritanceisgood,butthereisnogoodwaytodoit.”

A.SYNDER

Page 25: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

StructureoftheDecoratorPattern

EinführungindieSoftwaretechnik25

Intent:Weneedtoaddresponsibilitiestoexistingindividualobjectsdynamicallyandtransparently,withoutaffectingotherobjects.

Page 26: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Example:Decoratorinjava.io

EinführungindieSoftwaretechnik26

}  java.ioabstractsvariousdatasourcesanddestinations,aswellasprocessingalgorithms:}  Programsoperateonstreamobjects...}  independentlyofultimatedatasource/destination/shapeofdata.

Page 27: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

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.

Page 28: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Decorator:Problems

EinführungindieSoftwaretechnik28

}  Lotsoflittleobjects}  AdesignthatusesDecoratoroftenresultsinsystemscomposedoflotsoflittleobjectsthatalllookalike.

}  Objectsdifferonlyinthewaytheyareinterconnected,notintheirclassorinthevalueoftheirvariables.Imagineaclasstodrawaborderaroundacomponent..

}  Suchsystemsareeasytocustomizebythosewhounderstandthem,butcanbehardtolearnanddebug.

}  Objectidentity}  Adecoratoranditscomponentaren'tidentical.Fromanobjectidentitypointofview,adecoratedcomponentisnotidenticaltothecomponentitself.

}  Youshouldn'trelyonobjectidentitywhenyouusedecorators

Page 29: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

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();

Page 30: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Decorator:Problems

EinführungindieSoftwaretechnik30

}  Nolatebinding}  DELEGATIONVERSUSFORWARDSEMANTICS

Forwardingwithbindingofthistomethodholder;"ask"anobjecttodosomethingonitsown.

Bindingofthistomessagereceiver:“ask”anobjecttodosomethingonbehalfofthemessagereceiver.

Page 31: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

NoLateBinding:Example

EinführungindieSoftwaretechnik31

Page 32: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Decorator:Problems

EinführungindieSoftwaretechnik32

}  Needtoimplementforwardingmethodsforthosemethodsnotrelevanttothedecorator}  Alotofrepetitiveprogrammingwork}  Amaintenanceproblem:Whatifthedecoratedclasschanges

}  Addingnewmethodsorremovingmethodsthatareirrelevanttothedecorators

}  Decoratorclassesneedtochangeaswell}  Thisisavariantoftheso-called“fragilebaseclassproblem”

Page 33: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Decorator:Issues

EinführungindieSoftwaretechnik33

}  Keepthecommonclass(Component)lightweight:}  itshouldfocusondefininganinterface(e.g.implementedasinterface).

}  deferdefiningdatarepresentationtosubclasses.}  otherwisethecomplexityofComponentmightmakethedecoratorstooheavyweighttouseinquantity.

}  PuttingalotoffunctionalityintoComponentmakesitlikelythatsubclasseswillpayforfeaturestheydon'tneed.

}  Theseissuesrequirepre-planning.}  Difficulttoapplydecoratorpatternto3rd-partycomponentclass.

Page 34: Introduction to Software Technology 5. Design Patternsps.informatik.uni-tuebingen.de/teaching/ss18/se/6_design.pdf · Introduction to Software Technology 5. Design Patterns Klaus

Literature

EinführungindieSoftwaretechnik34

}  A.Shalloway,J.R.Trott.DesignPatternsExplained.Addison-Wesley,2005.}  Chap.9,14,15,18