DesignPatternsExplainedANewPerspective
onObject-OrientedDesignSecondEdition
ByAlanShalloway,JamesR.Trott
Publisher :AddisonWesleyProfessional
PubDate :October12,2004
ISBN :0-321-24714-0
Pages :480
Leveragethequalityandproductivitybenefitsofpatternswithoutthe
complexity!DesignPatternsExplained,SecondEditionisthefield'ssimplest,
clearest,mostpracticalintroductiontopatterns.Usingdozensofupdated
Javaexamples,itshowsprogrammersandarchitectsexactlyhowtouse
patternstodesign,develop,anddeliversoftwarefarmoreeffectively.
You'llstartwithacompleteoverviewofthefundamentalprinciplesof
patterns,andtheroleofobject-orientedanalysisanddesignincontemporary
softwaredevelopment.Then,usingeasy-to-understandsamplecode,Alan
ShallowayandJamesTrottilluminatedozensoftoday'smostusefulpatterns:
theirunderlyingconcepts,advantages,tradeoffs,implementationtechniques,
andpitfallstoavoid.ManypatternsareaccompaniedbyUMLdiagrams.
Tableof
Contents
• Index
•
Buildingontheirbest-sellingFirstEdition,ShallowayandTrotthave
thoroughlyupdatedthisbooktoreflectnewsoftwaredesigntrends,patterns,
andimplementationtechniques.Reflectingextensivereaderfeedback,they
havedeepenedandclarifiedcoveragethroughout,andreorganizedcontent
forevengreatereaseofunderstanding.Newandrevampedcoverageinthis
editionincludes
Betterwaystostart"thinkinginpatterns"
HowdesignpatternscanfacilitateagiledevelopmentusingeXtreme
Programmingandothermethods
Howtousecommonalityandvariabilityanalysistodesignapplication
architectures
Thekeyroleoftestingintoapatterns-drivendevelopmentprocess
Howtousefactoriestoinstantiateandmanageobjectsmore
effectively
TheObject-PoolPatternanewpatternnotidentifiedbythe"Gangof
Four"
Newstudy/practicequestionsattheendofeverychapter
Gentleyetthorough,thisbookassumesnopatternsexperiencewhatsoever.
It'stheideal"firstbook"onpatterns,andaperfectcomplementtoGamma's
classicDesignPatterns.Ifyou'reaprogrammerorarchitectwhowantsthe
clearestpossibleunderstandingofdesignpatternsorifyou'vestruggledto
makethemworkforyoureadthisbook.
DesignPatternsExplainedANewPerspective
onObject-OrientedDesignSecondEdition
By
AlanShalloway,JamesR.Trott
Publisher :AddisonWesleyProfessional
PubDate :October12,2004
Tableof
ISBN :0-321-24714-0
•
Contents
Pages :480
• Index
Copyright
PraiseforDesignPatternsExplained,SecondEdition:
TheSoftwarePatternsSeries
Titlesintheseries:
Preface
FromObjectOrientationtoPatternstoTrueObjectOrientation
FromArtificialIntelligencetoPatternstoTrueObjectOrientation
ANoteAboutConventionsUsedinThisBook
Feedback
NewintheSecondEdition
Acknowledgments
PartI.
AnIntroductiontoObject-OrientedSoftwareDevelopment
Chapter1.
TheObject-OrientedParadigm
Overview
BeforetheObject-OrientedParadigm:FunctionalDecomposition
TheProblemofRequirements
DealingwithChanges:UsingFunctionalDecomposition
DealingwithChangingRequirements
TheObject-OrientedParadigm
Object-OrientedProgramminginAction
SpecialObjectMethods
Summary
ReviewQuestions
Chapter2.
TheUMLTheUnifiedModelingLanguage
Overview
WhatIstheUML?
WhyUsetheUML?
TheClassDiagram
InteractionDiagrams
Summary
ReviewQuestions
PartII.
TheLimitationsofTraditionalObject-OrientedDesign
Chapter3.
AProblemThatCriesOutforFlexibleCode
Overview
ExtractingInformationfromaCAD/CAMSystem
UnderstandtheVocabulary
DescribetheProblem
TheEssentialChallengesandApproaches
Summary
ReviewQuestions
Chapter4.
AStandardObject-OrientedSolution
Overview
SolvingwithSpecialCases
Summary
ReviewQuestions
PartIII.
DesignPatterns
Chapter5.
AnIntroductiontoDesignPatterns
Overview
DesignPatternsArosefromArchitectureandAnthropology
MovingfromArchitecturaltoSoftwareDesignPatterns
WhyStudyDesignPatterns?
OtherAdvantagesofStudyingDesignPatterns
Summary
ReviewQuestions
Chapter6.
TheFacadePattern
Overview
IntroducingtheFacadePattern
LearningtheFacadePattern
FieldNotes:TheFacadePattern
RelatingtheFacadePatterntotheCAD/CAMProblem
Summary
ReviewQuestions
Chapter7.
TheAdapterPattern
Overview
IntroducingtheAdapterPattern
LearningtheAdapterPattern
FieldNotes:TheAdapterPattern
RelatingtheAdapterPatterntotheCAD/CAMProblem
Summary
ReviewQuestions
Chapter8.
ExpandingOurHorizons
Overview
Objects:TheTraditionalViewandtheNewView
Encapsulation:TheTraditionalViewandtheNewView
FindWhatIsVaryingandEncapsulateIt
CommonalityandVariabilityAnalysisandAbstractClasses
TheQualitiesofAgileCoding
Summary
ReviewQuestions
Chapter9.
TheStrategyPattern
Overview
AnApproachtoHandlingNewRequirements
TheInternationalE-CommerceSystemCaseStudy:InitialRequirements
HandlingNewRequirements
TheStrategyPattern
FieldNotes:UsingtheStrategyPattern
Summary
ReviewQuestions
Chapter10.
TheBridgePattern
Overview
IntroducingtheBridgePattern
LearningtheBridgePattern:AnExample
AnObservationAboutUsingDesignPatterns
LearningtheBridgePattern:DerivingIt
TheBridgePatterninRetrospect
FieldNotes:UsingtheBridgePattern
Summary
ReviewQuestions
Chapter11.
TheAbstractFactoryPattern
Overview
IntroducingtheAbstractFactoryPattern
LearningtheAbstractFactoryPattern:AnExample
LearningtheAbstractFactoryPattern:ImplementingIt
FieldNotes:TheAbstractFactoryPattern
RelatingtheAbstractFactoryPatterntotheCAD/CAMProblem
Summary
ReviewQuestions
PartIV.
PuttingItAllTogether:ThinkinginPatterns
Chapter12.
HowDoExpertsDesign?
Overview
BuildingbyAddingDistinctions
Summary
ReviewQuestions
Chapter13.
SolvingtheCAD/CAMProblemwithPatterns
Overview
ReviewoftheCAD/CAMProblem
ThinkinginPatterns
ThinkinginPatterns:Step1
ThinkinginPatterns:Step2a
ThinkinginPatterns:Step2b
ThinkinginPatterns:Step2c
ThinkinginPatterns:Steps2aand2bRepeated(Facade)
ThinkinginPatterns:Steps2aand2bRepeated(Adapter)
ThinkinginPatterns:Steps2aand2bRepeated(AbstractFactory)
ThinkinginPatterns:Step3
ComparisonwiththePreviousSolution
Summary
ReviewQuestions
PartV.
TowardaNewParadigmofDesign
Chapter14.
ThePrinciplesandStrategiesofDesignPatterns
Overview
TheOpen-ClosedPrinciple
ThePrincipleofDesigningfromContext
ThePrincipleofEncapsulatingVariation
AbstractClassesvs.Interfaces
ThePrincipleofHealthySkepticism
Summary
ReviewQuestions
Chapter15.
CommonalityandVariabilityAnalysis
Overview
CommonalityandVariabilityAnalysisandApplicationDesign
SolvingtheCAD/CAMProblemwithCVA
Summary
ReviewQuestions
Chapter16.
TheAnalysisMatrix
Overview
IntheRealWorld:Variations
TheInternationalE-CommerceSystemCaseStudy:HandlingVariation
FieldNotes
Summary
ReviewQuestions
Chapter17.
TheDecoratorPattern
Overview
ALittleMoreDetail
TheDecoratorPattern
ApplyingtheDecoratorPatterntotheCaseStudy
AnotherExample:Input/Output
FieldNotes:UsingtheDecoratorPattern
TheEssenceoftheDecoratorPattern
Summary
ReviewQuestions
PartVI.
OtherValuesofPatterns
Chapter18.
TheObserverPattern
Overview
CategoriesofPatterns
MoreRequirementsfortheInternationalE-CommerceCaseStudy
TheObserverPattern
ApplyingtheObservertotheCaseStudy
FieldNotes:UsingtheObserverPattern
Summary
ReviewQuestions
Chapter19.
TheTemplateMethodPattern
Overview
MoreRequirementsfortheInternationalE-CommerceCaseStudy
TheTemplateMethodPattern
ApplyingtheTemplateMethodtotheInternationalE-CommerceCaseStudy
UsingtheTemplateMethodPatterntoReduceRedundancy
FieldNotes:UsingtheTemplateMethodPattern
Summary
ReviewQuestions
PartVII.
Factories
Chapter20.
LessonsfromDesignPatterns:Factories
Overview
Factories
TheUniversalContextRevisited
FactoriesFollowOurGuidelines
LimitingtheVectorsofChange
AnotherWaytoThinkAboutIt
DifferentRolesofFactories
FieldNotes
Summary
ReviewQuestions
Chapter21.
TheSingletonPatternandtheDouble-CheckedLockingPattern
Overview
IntroducingtheSingletonPattern
ApplyingtheSingletonPatterntotheCaseStudy
AVariant:TheDouble-CheckedLockingPattern
Reflections
FieldNotes:UsingtheSingletonandDouble-CheckedLockingPatterns
Summary
ReviewQuestions
Chapter22.
TheObjectPoolPattern
Overview
AProblemRequiringtheManagementofObjects
TheObjectPoolPattern
Observation:FactoriesCanDoMuchMoreThanInstantiation
Summary
ReviewQuestions
Chapter23.
TheFactoryMethodPattern
Overview
MoreRequirementsfortheCaseStudy
TheFactoryMethodPattern
FactoryMethodPatternandObject-OrientedLanguages
FieldNotes:UsingtheFactoryMethodPattern
Summary
ReviewQuestions
Chapter24.
SummaryofFactories
Overview
StepsintheSoftwareProcess
ParallelsinFactoriesandXPPractices
ScalingSystems
PartVIII.
EndingsandBeginnings
Chapter25.
DesignPatternsReviewed:ASummationandaBeginning
Overview
ASummaryofObject-OrientedPrinciples
HowDesignPatternsEncapsulateImplementations
CommonalityandVariabilityAnalysisandDesignPatterns
DecomposingaProblemDomainintoResponsibilities
PatternsandContextualDesign
RelationshipsWithinaPattern
DesignPatternsandAgileCodingPractices
FieldNotes
Summary
ReviewQuestions
Chapter26.
Bibliography
DesignPatternsExplained:TheWebSiteCompanion
RecommendedReading
RecommendedReadingforJavaProgrammers
RecommendedReadingforC++Programmers
RecommendedReadingforCOBOLProgrammers
RecommendedReadingoneXtremeProgramming
RecommendedReadingonGeneralProgramming
PersonalFavorites
Index
Copyright
Theauthorsandpublisherhavetakencareinthepreparationofthis
book,butmakenoexpressedorimpliedwarrantyofanykindand
assumenoresponsibilityforerrorsoromissions.Noliabilityisassumed
forincidentalorconsequentialdamagesinconnectionwithorarisingout
oftheuseoftheinformationorprogramscontainedherein.
Publisher:JohnWait
AcquisitionsEditor:JohnNeidhart
ExecutiveEditor:StephaneNakib
EditorialAssistant:EbonyHaight
MarketingManager:CurtJohnson
Publicity:JoanMurray
ManagingEditor:GinaKanouse
SeniorProjectEditor:SarahKearns
ProductionEditor:KerryReardon
ManufacturingBuyer:DanUhrig
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Wherethose
designationsappearinthisbook,andAddison-Wesleywasawareofa
trademarkclaim,thedesignationshavebeenprintedwithinitialcapital
lettersorinallcapitals.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityfor
bulkpurchasesandspecialsales.Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419
ForsalesoutsideoftheU.S.,pleasecontact:InternationalSales
VisitAddison-WesleyontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationDataLOC2004108740
Copyright©2005byPearsonEducation,Inc.
Allrightsreserved.Nopartofthispublicationmaybereproduced,stored
inaretrievalsystem,ortransmitted,inanyform,orbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,withoutthe
priorconsentofthepublisher.PrintedintheUnitedStatesofAmerica.
PublishedsimultaneouslyinCanada.
Forinformationonobtainingpermissionforuseofmaterialfromthis
work,pleasesubmitawrittenrequestto:PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
Textprintedonrecycledpaper
12345678910MA0605040302
Firstprinting,October2004
Dedication
ToLeigh,Bryan,Lisa,Michael,andStevenfortheirlove,support,
encouragement,andsacrifice.
AlanShalloway
ToJill,Erika,Lorien,Mikaela,andGeneva,therosesinthegardenofmy
life.solagloriaDeiJamesR.Trott
PraiseforDesignPatternsExplained,
SecondEdition:
Theexplanationoffundamentalobject-orientedconcepts
throughoutisexceptional.Ihavestruggledtoteachsimilar
conceptstobeginnersinmyclassesandIdefinitelyplantoborrow
someoftheauthors'approaches(andrecommendthebook,of
course)!
CLIFNOCK
Well-written,thought-provoking,andveryenlightening.Amustreadforanyoneinterestedindesignpatternsandobject-oriented
development.
JAMESHUDDLESTON
TheSoftwarePatternsSeries
SeriesEditor:JohnM.VlissidesTheSoftwarePatternsSeries(SPS)
comprisespatternliteratureoflastingsignificancetosoftwaredevelopers.
Softwarepatternsdocumentgeneralsolutionstorecurringproblemsinall
software-relatedspheres,fromthetechnologyitself,totheorganizations
thatdevelopanddistributeit,tothepeoplewhouseit.Booksinthe
seriesdistillexperiencefromoneormoreoftheseareasintoaformthat
softwareprofessionalscanapplyimmediately.
RelevanceandimpactarethetenetsoftheSPS.Relevancemeanseach
bookpresentspatternsthatsolverealproblems.Patternsworthyofthe
nameareintrinsicallyrelevant;theyareborneofpractitioners'
experiences,nottheoryorspeculation.Patternshaveimpactwhenthey
changehowpeopleworkforthebetter.Abookbecomesapartofthe
seriesnotjustbecauseitembracesthesetenets,butbecauseithas
demonstrateditfulfillsthemforitsaudience.
Titlesintheseries:
DataAccessPatterns:DatabaseInteractionsinObject-Oriented
Applications,CliftonNockDesignPatternsinC#,StevenJohnMetsker
DesignPatternsExplained:ANewPerspectiveonObject-Oriented
Design,AlanShalloway/JamesR.TrottDesignPatternsJava™
Workbook,StevenJohnMetsker
TheDesignPatternsSmalltalkCompanion,ShermanAlpert/Kyle
Brown/BobbyWoolfTheJoyofPatterns:UsingPatternsforEnterprise
Development,BrandonGoldfedderTheManagerPool:Patternsfor
RadicalLeadership,DonOlson/CarolStimmel.NETPatterns:
Architecture,Design,andProcess,ChristianThilmanyPatternHatching:
DesignPatternsApplied,JohnVlissides
PatternLanguagesofProgramDesign,editedbyJamesO.
Coplien/DouglasC.SchmidtPatternLanguagesofProgramDesign2,
editedbyJohnM.Vlissides/JamesO.Coplien/NormanL.KerthPattern
LanguagesofProgramDesign3,editedbyRobertMartin/Dirk
Riehle/FrankBuschmannSmallMemorySoftware,JamesNoble/Charles
Weir
SoftwareConfigurationManagementPatterns,StephenP.Berczuk/Brad
AppletonFormoreinformation,checkouttheserieswebsiteat
www.awprofessional.com/series/swpatterns
Preface
ShouldYouBuytheSecondEditionIfYouAlreadyOwnthe
First?
Theanswer,ofcourse,isyes!Here'swhy.
Sincethefirsteditionwaswritten,wehavelearnedsomuchmoreaboutdesignpatterns,
includingthefollowing:
Howtousecommonalityandvariabilityanalysistodesignapplicationarchitectures
HowdesignpatternsrelatetoandactuallyfacilitateeXtremeprogramming(XP)and
agiledevelopment.
Howtestingisafirstprincipleofqualitycoding.
Whytheuseoffactoriestoinstantiateandmanageobjectsiscritical
Whichsetofpatternsareessentialforstudentstohelpthemlearnhowtothinkin
patterns
Thisbookcoversallofthesetopics.Wehavedeepenedandclarifiedwhatwehadbefore
andhaveaddedsomenewcontentthatyouwillfindveryhelpful,includingthefollowing:
Chapter15:CommonalityandVariabilityAnalysis
Chapter20:LessonsfromDesignPatterns:Factories
Chapter21:TheObject-PoolPattern(apatternnotcoveredbytheGangofFour)
Chapter22:FactoriesSummarized
Wehavechangedtheorderinwhichwepresentsomeofthepatterns.Thissequenceis
morehelpfulforthestudentsinourcoursesastheylearntheideasbehindpatterns.
Wehavetouchedeverychapter,incorporatingthefeedbackwehavereceivedfromour
manyreadersoverthesepastthreeyears.
And,tohelpstudents,wehavecreatedstudyquestionsforeachchapter(withanswerson
thebook'scompanionWebsite).
Wecanhonestlysaythisisoneofthefewsecondeditionsthatisdefinitelyworthbuying
evenifyouhavethefirstone.
Wewouldlovetohearwhatyouthink.
AlanandJim
Designpatternsandobject-orientedprogramming.Theyholdsuch
promisetomakeyourlifeasasoftwaredesigneranddevelopereasier.
Theirterminologyisbandiedabouteverydayinthetechnicalandeven
thepopularpress.Itcanbehardtolearnthem,however,tobecome
proficientwiththem,tounderstandwhatisreallygoingon.
Perhapsyouhavebeenusinganobject-orientedorobject-based
languageforyears.Haveyoulearnedthatthetruepowerofobjectsisnot
inheritance,butisin"encapsulatingbehaviors"?Perhapsyouarecurious
aboutdesignpatternsandhavefoundtheliteratureabittooesotericand
high-falutin.Ifso,thisbookisforyou.
Itisbasedonyearsofteachingthismaterialtosoftwaredevelopers,both
experiencedandnewtoobjectorientation.Itisbaseduponthebeliefand
ourexperiencethatwhenyouunderstandthebasicprinciplesand
motivationsthatunderlietheseconcepts,whytheyaredoingwhatthey
do,yourlearningcurvewillbeincrediblyshorter.Andinourdiscussionof
designpatterns,youwillunderstandthetruemindsetofobject
orientation,whichisanecessitybeforeyoucanbecomeproficient.
Asyoureadthisbook,youwillgainasolidunderstandingof12core
designpatternsandapatternusedinanalysis.Youwilllearnthatdesign
patternsdonotexistinisolation,butworkinconcertwithotherdesign
patternstohelpyoucreatemorerobustapplications.Youwillgain
enoughofafoundationthatyouwillbeabletoreadthedesignpattern
literature,ifyouwantto,andpossiblydiscoverpatternsonyourown.
Mostimportantly,youwillbebetterequippedtocreateflexibleand
completesoftwarethatiseasiertomaintain.
Althoughthe12patternsweteachherearenotallofthepatternsyou
shouldlearn,anunderstandingofthesewillenableyoutolearnthe
othersonyourownmoreeasily.Insteadofgivingyoumorepatternsthan
youneedtogetstarted,wehaveincludedpattern-relatedissuesthatwill
bemoreuseful.
FromObjectOrientationtoPatternstoTrue
ObjectOrientation
Inmanyways,thisbookisaretellingofmypersonalexperiencelearning
designpatterns.Thisstartedwithlearningthepatternsthemselvesand
thenlearningtheprinciplesbehindthem.Iexpandedthisunderstanding
intotherealmsofanalysisandtestingaswellaslearninghowpatterns
relatetoagilecodingmethods.Thissecondeditionofthisbookincludes
manyadditionalinsightsIhavehadsincepublicationofthefirstedition.
Priortostudyingdesignpatterns,Iconsideredmyselftobereasonably
expertinobject-orientedanalysisanddesign.Mytrackrecordhad
includedseveralfairlyimpressivedesignsandimplementationsinmany
industries.IknewC++andwasbeginningtolearnJava.Theobjectsin
mycodewerewell-formedandtightlyencapsulated.Icoulddesign
excellentdataabstractionsforinheritancehierarchies.IthoughtIknew
objectorientation.
Now,lookingback,IseethatIreallydidnotunderstandthefull
capabilitiesofobject-orienteddesign,eventhoughIwasdoingthingsthe
waymostexpertsadvised.Itwasn'tuntilIbegantolearndesignpatterns
thatmyobject-orienteddesignabilitiesexpandedanddeepened.
Knowingdesignpatternshasmademeabetterdesigner,evenwhenI
don'tusethesepatternsdirectly.
Ibeganstudyingdesignpatternsin1996.IwasaC++/object-oriented
designmentoratalargeaerospacecompanyintheNorthwest.Several
peopleaskedmetoleadadesignpatternstudygroup.That'swhereI
metmycoauthor,JimTrott.Inthestudygroup,severalinterestingthings
happened.First,Igrewfascinatedwithdesignpatterns.Ilovedbeing
abletocomparemydesignswiththedesignsofotherswhohadmore
experiencethanI.Andsecond,IdiscoveredthatIwasnottakingfull
advantageofdesigningtointerfacesandthatIdidn'talwaysconcern
myselfwithseeingwhetherIcouldhaveanobjectuseanotherobject
withoutknowingtheusedobject'stype.Ialsonoticedthatbeginnersin
object-orienteddesignthosewhowouldnormallybedeemedaslearning
designpatternstooearlywerebenefitingasmuchfromthestudygroup
astheexpertswere.Thepatternspresentedexamplesofexcellent
object-orienteddesignsandillustratedbasicobject-orientedprinciples,
whichhelpedtomaturetheirdesignsmorequickly.Bytheendofthe
studysessions,Iwasconvincedthatdesignpatternswerethegreatest
thingtohappentosoftwaredesignsincetheinventionofobject-oriented
design.
WhenIlookedatmyworkatthetime,however,IsawthatIwasnot
incorporatinganydesignpatternsintomycode.Or,atleast,not
consciously.Later,afterlearningpatterns,IrealizedIhadincorporated
manydesignpatternsintomycodejustoutofbeingagoodcoder.
However,nowthatIunderstandpatternsbetter,Iamabletousethem
better.
IjustfiguredIdidn'tknowenoughdesignpatternsyetandneededto
learnmore.Atthetime,Ionlyknewaboutsixofthem.ThenIhadan
epiphany.Iwasworkingasamentorinobject-orienteddesignfora
projectandwasaskedtocreatetheproject'shigh-leveldesign.The
leaderoftheprojectwasextremelysharp,butwasfairlynewtoobjectorienteddesign.
Theproblemitselfwasn'tthatdifficult,butitrequiredagreatdealof
attentiontomakesurethecodewasgoingtobeeasytomaintain.
Literally,afterabouttwominutesoflookingattheproblem,Ihad
developedadesignbasedonmynormalapproachofdataabstraction.
Unfortunately,itwasalsocleartomethiswasnotgoingtobeagood
design.Dataabstractionalonehadfailedme.Ihadtofindsomething
better.
Twohourslater,afterapplyingeverydesigntechniqueIknew,Iwasno
betteroff.Mydesignwasessentiallythesame.Whatwasmost
frustratingwasthatIknewtherewasabetterdesign.Ijustcouldn'tseeit.
Ironically,Ialsoknewoffourdesignpatternsthat"lived"inmyproblem,
butIcouldn'tseehowtousethem.HereIwasasupposedexpertin
object-orienteddesignbaffledbyasimpleproblem!
Feelingveryfrustrated,Itookabreakandstartedwalkingdownthehall
toclearmyhead,tellingmyselfIwouldnotthinkoftheproblemforat
least10minutes.Well,30secondslater,Iwasthinkingaboutitagain!
ButIhadgottenaninsightthatchangedmyviewofdesignpatterns:
ratherthanusingpatternsasindividualitems,Ishouldusethedesign
patternstogether.
Patternsaresupposedtobesewntogethertosolveaproblem.
Ihadheardthisbefore,buthadn'treallyunderstoodit.Becausepatterns
insoftwarehavebeenintroducedasdesignpatterns,Ihadalways
laboredundertheassumptionthattheyhadmostlytodowithdesign.My
thoughtswerethatinthedesignworld,thepatternscameasprettymuch
well-formedrelationshipsbetweenclasses.ThenIreadChristopher
Alexander'samazingbook,TheTimelessWayofBuilding(Oxford
UniversityPress,1979).Ilearnedthatpatternsexistedatall
levelsanalysis,design,andimplementation.Alexanderdiscussesusing
patternstohelpintheunderstandingoftheproblemdomain(evenin
describingit),notjustusingthemtocreatethedesignaftertheproblem
domainisunderstood.
Mymistakehadbeenintryingtocreatetheclassesinmyproblem
domainandthenstitchthemtogethertomakeafinalsystem,aprocess
thatAlexandercallsaparticularlybadidea.IhadneveraskedwhetherI
hadtherightclassesbecausetheyjustseemedsoright,soobvious;they
weretheclassesthatimmediatelycametomindasIstartedmyanalysis,
the"nouns"inthedescriptionofthesystemthatwehadbeentaughtto
lookfor.ButIhadstruggledtryingtopiecethemtogether.
WhenIsteppedbackanduseddesignpatternsandAlexander's
approachtoguidemeinthecreationofmyclasses,afarsuperior
solutionunfoldedinonlyamatterofminutes.Itwasagooddesign,and
weputitintoproduction.Iwasexcitedexcitedtohavedesignedagood
solutionandexcitedaboutthepowerofdesignpatterns.ItwasthenthatI
startedincorporatingdesignpatternsintomydevelopmentworkandmy
teaching.
Ibegantodiscoverthatprogrammerswhowerenewtoobject-oriented
designcouldlearndesignpatterns,andindoingso,developabasicset
ofobject-orienteddesignskills.Itwastrueforme,anditwastrueforthe
studentswhomIwasteaching.
Imaginemysurprise!ThedesignpatternbooksIhadbeenreadingand
thedesignpatternexpertsIhadbeentalkingtoweresayingthatyou
reallyneededtohaveagoodgroundinginobject-orienteddesignbefore
embarkingonastudyofdesignpatterns.Nevertheless,Isaw,withmy
owneyes,studentswholearnedobject-orienteddesignconcurrentlywith
designpatternslearnedobject-orienteddesignfasterthanthosejust
studyingobject-orienteddesign.Theyevenseemedtolearndesign
patternsatalmostthesamerateasexperiencedobject-oriented
practitioners.
Ibegantousedesignpatternsasabasisformyteaching.Ibegantocall
myclassesPattern-OrientedDesign:DesignPatternsfromAnalysisto
Implementation.
Iwantedmystudentstounderstandthesepatternsandbeganto
discoverthatusinganexploratoryapproachwasthebestwaytofoster
thisunderstanding.Forinstance,Ifoundthatitwasbettertopresentthe
Bridgepatternbypresentingaproblemandthenhavemystudentstryto
designasolutiontotheproblemusingafewguidingprinciplesand
strategiesthatIhadfoundwerepresentinmostofthepatterns.Intheir
exploration,thestudentsdiscoveredthesolutionessentiallytheBridge
patternandrememberedit.