ebook img

Design Patterns PDF

305 Pages·2007·16.899 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Design Patterns

Design Patterns Christopher G. Lasater Wordware Publishing, Inc. LibraryofCongressCataloging-in-PublicationData Lasater,ChristopherG. DesignPatterns/byChristopherG.Lasater. p.cm. Includesindex. ISBN-10:1-59822-031-4(pbk.) ISBN-13:978-1-59822-031-5 1. Softwarepatterns. 2. Object-orientedprogramming(Computer science). I.Title. QA76.76.P37L372006 005.1--dc22 2006027625 ©2007,WordwarePublishing,Inc. AllRightsReserved 1100SummitAvenue,Suite102 Plano,Texas75074 Nopartofthisbookmaybereproducedinanyformorby anymeanswithoutpermissioninwritingfrom WordwarePublishing,Inc. PrintedintheUnitedStatesofAmerica ISBN-10:1-59822-031-4 ISBN-13:978-1-59822-031-5 10 9 8 7 6 5 4 3 2 1 0609 Allbrandnamesandproductnamesmentionedinthisbookaretrademarksorservicemarksof theirrespectivecompanies.Anyomissionormisuse(ofanykind)ofservicemarksortrademarks shouldnotberegardedasintenttoinfringeonthepropertyofothers.Thepublisherrecognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguishtheirproducts. Thisbookissoldasis,withoutwarrantyofanykind,eitherexpressorimplied,respectingthe contentsofthisbookandanydisksorprogramsthatmayaccompanyit,includingbutnotlimited to implied warranties for the book’s quality, performance, merchantability, or fitness for any particularpurpose.NeitherWordwarePublishing,Inc.noritsdealersordistributorsshallbe liabletothepurchaseroranyotherpersonorentitywithrespecttoanyliability,loss,ordamage causedorallegedtohavebeencauseddirectlyorindirectlybythisbook. AllinquiriesforvolumepurchasesofthisbookshouldbeaddressedtoWordware Publishing, Inc., at the above address. Telephone inquiries may be made by calling: (972)423-0090 ToLorenzoandLena.WithoutthemIwouldn’thavehad thestrengthorcouragetowritethisbook. This page intentionally left blank. Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii AudienceandGoal. . . . . . . . . . . . . . . . . . . . . . . . . x AssumptionsThisBookMakes . . . . . . . . . . . . . . . . . xi ConventionsUsedinThisBook . . . . . . . . . . . . . . . . xii UsingCodeExamples. . . . . . . . . . . . . . . . . . . . . . xiii Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1 Why Pattern? . . . . . . . . . . . . . . . . . . . . . . . 1 CommonAspectsofObject-OrientedLanguages. . . . . . . . 2 PatternsCross-ReferenceEachOther . . . . . . . . . . . . . 14 RefactoringLegacyCodeandImprovingNewCode. . . . . . 15 ReflectionandOOP . . . . . . . . . . . . . . . . . . . . . . . 16 2 Creational Patterns . . . . . . . . . . . . . . . . . . . 17 FactoryPattern. . . . . . . . . . . . . . . . . . . . . . . . . . 18 AbstractFactoryPattern. . . . . . . . . . . . . . . . . . . . . 41 BuilderPattern. . . . . . . . . . . . . . . . . . . . . . . . . . 57 PrototypePattern . . . . . . . . . . . . . . . . . . . . . . . . 74 SingletonPattern. . . . . . . . . . . . . . . . . . . . . . . . . 81 3 Behavioral Patterns . . . . . . . . . . . . . . . . . . . 91 ChainofResponsibilityPattern . . . . . . . . . . . . . . . . . 92 CommandPattern . . . . . . . . . . . . . . . . . . . . . . . . 99 InterpreterPattern . . . . . . . . . . . . . . . . . . . . . . . 108 IteratorPattern . . . . . . . . . . . . . . . . . . . . . . . . . 120 MediatorPattern . . . . . . . . . . . . . . . . . . . . . . . . 128 v MementoPattern. . . . . . . . . . . . . . . . . . . . . . . . 136 ObserverPattern . . . . . . . . . . . . . . . . . . . . . . . . 145 StatePattern . . . . . . . . . . . . . . . . . . . . . . . . . . 154 StrategyPattern. . . . . . . . . . . . . . . . . . . . . . . . . 174 TemplatePattern . . . . . . . . . . . . . . . . . . . . . . . . 184 VisitorPattern . . . . . . . . . . . . . . . . . . . . . . . . . 193 4 Structural Patterns . . . . . . . . . . . . . . . . . . . 205 AdapterPattern. . . . . . . . . . . . . . . . . . . . . . . . . 206 BridgePattern. . . . . . . . . . . . . . . . . . . . . . . . . . 214 CompositePattern . . . . . . . . . . . . . . . . . . . . . . . 224 DecoratorPattern. . . . . . . . . . . . . . . . . . . . . . . . 235 FacadePattern . . . . . . . . . . . . . . . . . . . . . . . . . 246 FlyweightPattern. . . . . . . . . . . . . . . . . . . . . . . . 255 ProxyPattern . . . . . . . . . . . . . . . . . . . . . . . . . . 269 GlossaryofTerms . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 vi Introduction Designpatternshavebeenaroundforquiteafewyears. TheywereoriginallycreatedbytheGangofFour(Erich Gamma,RichardHelm,RalphJohnson,andJohn Vlissides),whichisresponsibleforformalizingtheaccepted designpatternsweusetoday.Theiruse,whilequestioned andarguedoverbydifferentprogrammingschoolsof thought,hasgenerallybeenacceptedas“bestpractices” withinthedevelopmentcommunity.Theoriginaltakeoffof designpatternswasbroughtaboutintheJavaandC++ world. Otherlanguageslike.NET(dotNET)havesprungupin recentyearstofillcertainmarketingandtechnologyvoids leftopenbytheselanguages,andhaveadopteddesignpat- ternsinonewayoranothertomimicwhatwaslearnedby programmersinJavaandC++.Eventhepreviously script-orientedsyntaxofVisualBasichasblossomedintoa fullyobject-orientedlanguage,viaVisualBasic.NET. MicrosoftalsoaddedaJava-likelanguage,whichhas relatedsyntaxandframeworkstructure,intheformofC#, whichissomuchlikeJavathatapplyingdesignpatternsis arelativelyexpectedconjecture. Mostprogrammersnewtoobject-orientedlanguagesseem tohavethesamedilemmawhenfacedwithwhetherornot touseorlearndesignpatterns:WhyshouldI?Usuallythe problemisthattheabilityandtimerequiredforlearning patterns-basedprogrammingisatapremiumandthe returnseemsdubious.Someonenotfamiliarwiththewhy vii Introduction behindthemethodologycertainlywillnotcontinueonto thewhatandwhere.Soexplainingtopeoplenewtothe conceptwhytheyshouldspendthetimelearningdesign patternscanbedifficult. Anotherissueisavailabilityandeaseofdisseminationof therelevantdata.Therehavebeennumerousbooksand paperswrittenontheusesandmethodologyofdesignpat- terns,buttoajuniordeveloperlookingtoimprovebasic skillsorlearntheskillsneededtogetajob,havingtoread complicatedtextstolearnanewmethodologyorwayof thinkingisoutofthequestion.Seniordeveloperslookingto upgradecurrentskillscanhavesimilarissues,inthatto augmenttheirskillsetstheyhavetodoalargeamountof researchjusttobeabletounderstandthebasics.Mostof thetextsavailableondesignpatternsarenoteasilyrefer- enced,andrequireanexpandedunderstandingof object-orientedmethodologiesandpatternstoevenget through,andfullcomprehensionmayrequirereadingthe materialseveraltimesfromstarttofinish.Therehavebeen afewattemptsto“dumbdown”thedata,buttheseseemto bemoreplayfulthanuseful,andleaveprojectdevelopersa littleturnedoffbythelackofseriouscontentofthework. Asadeveloper,aswellasadevelopmentmanager,Ican assureyouIhavehadthesameproblems.Whetherlearning tousepatternsorteachingthemtoothers,Ifoundthere wasnoquickandeasyreferencetoexplainorlearnwhich patternisappropriateinwhichcaseandwhy.Ioftenstrug- gledwiththebasicsofobject-orienteddesignwhen learningpatterns,andhadtolearnthehardwaywhich methodsworkedwhere.OnethingIdidfindwasthat designpatternswerecreatedandhaveevolvedfromthe workofeverydaycodepractices,andmanydevelopersare viii Introduction usingthemwithoutactuallyknowingtheestablished23 patterns.WhenIfirststartedtopattern,Ioftenhadto searchthroughmanytextsandwebsites,accessingseveral sourcestounderstandaparticularpattern.Thiswashard whentryingtomeetdeadlines,sincetimewascrucial,and theonlyreasonIpersistedinlearningwasbecauseIsaw therewasalotofvalueinwhatIdidmanageto understand. Afterseveralyearsofthiskindofthing,Ibeganto writesomearticlesfortheCodeProjectsite (www.codeproject.com).Istartedwithaspectsofthings aboutwhichIsawvalue,butIthoughtwereunder- documented.IwroteinafashionthatIwouldliketoread, somethingwithoutalotofcomplicateddialogthatjust statedproblemsandsolutionsincodeandexplanationsof whatIwasdoingandwhy.AfterawhileIrealizedalotof peopleseemedtorespondtowhatIhadwritten.Thatwas whenIdecidedthatIshouldwritethisbook. ix

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.