How to Learn Design Patterns | scraggo.com
文章推薦指數: 80 %
It's a Creational pattern of low complexity. (refactoring.guru also gives it a medium rating in terms of popularity.) The word “singleton” is ... I’velongbeenintriguedbydesignpatterns,butwhenIstartedlearningthem,IrealizedquicklythatIdidn’thaveaclearlearningpath.Ididn’tknowhowIshouldlearndesignpatternsorifit’stherighttimeformetolearnthem. So,Isoughtouttoanswersomequestions:Whataretheprerequisitesforlearningdesignpatterns?WhatmaterialshouldIuseandhowdoIavoidbeingscattered?HowdoIputthemintopractice? ThisarticleisacontinuationofapreviouspostwhereIintroduceddesignpatternsanddiscussedthe“what”andthe“why”ofthem.Thispostaimstogiveyouacurriculumforlearningdesignpatternsandresourcesthathavehelpedme. Prerequisites Hereareafewsuggestionsbeforecrackingopenafatbookondesignpatterns: Makeatleastoneprogramofmediumorhighercomplexityonyourown.Withoutthis,youmaylackcontextthatcomesfromencounteringatleastoneproblemthatdesignpatternssolve. Getfamiliarwithobject-orientedprogramming,ie-classes,properties,methods,instantiation,inheritance,etc.(Ifyou’reaJavaScriptdeveloper,itwouldbeadvantageoustobefamiliarwithTypeScriptandusethattolearnthepatterns.) https://github.com/scraggo/design-patterns-refactoring-guru/ https://www.typescriptlang.org/docs/handbook/release-notes/overview.html LearnhowtocreateUML(UnifiedModelingLanguage)classdiagrams.They’repopularandeffectiveforvisuallysummarizinghigherlevelconcepts-especiallydesignpatterns. UMLClassDiagram-TutorialAndExamplehttps://www.tutorialandexample.com/class-diagram/ UMLClassDiagramTutorialhttps://www.visual-paradigm.com/guide/uml-unified-modeling-language/uml-class-diagram-tutorial/ UMLClassDiagramTutorialwithExampleshttps://www.guru99.com/uml-class-diagram.html DesignPatterns101:GettingStarted Classifyingdesignpatterns Let’sbeginbyunderstandinghowtoclassifythedesignpatterns: “Designpatternsdifferbytheircomplexity,levelofdetailandscaleofapplicability.Inaddition,theycanbecategorizedbytheirintentanddividedintothreegroups.Creationalpatternsprovideobjectcreationmechanismsthatincreaseflexibilityandreuseofexistingcode.Structuralpatternsexplainhowtoassembleobjectsandclassesintolargerstructures,whilekeepingthestructuresflexibleandefficient.Behavioralpatternstakecareofeffectivecommunicationandtheassignmentofresponsibilitiesbetweenobjects.” Classifyingthepatternswillhelpgiveyoualay-of-the-land.You’llbemoreorientedwhilelearningthem.AgoodfirstpatternforclassificationistheSingletonpattern.It’saCreationalpatternoflowcomplexity.(refactoring.gurualsogivesitamediumratingintermsofpopularity.) Theword“singleton”ishelpfulbecausethepatternacknowledgestheuseofthewordinEnglish:”asinglethingofthekindunderconsideration.”Itmakesiteasytorememberitsintent,”ensuringthataclasshasonlyoneinstance,whileprovidingaglobalaccesspointtothisinstance.” Learningthroughanalogiescanbeahugementalbenefit.Wecanunderstandthecorrespondingconceptsmoredeeplybecausewecanrelatetothemoutsideofprogramming.Forexample,theDecoratorpattern(aStructuralpattern)providespowerfulimageryofRussiandollswhichrepresent“layering.”Onceyou’vegottheanalogyandyou’vestudiedthemethodswiththeterminologyinmind,it’llbedifficulttoforgetA)thepatterncategoryandB)howitworks. “Affordances”(summarizingdesignpatterns) Wecanclassifythepatternsevenfurther.Eachpatternaddresses a“problem”unrelatedtoanypattern an“intent”thatprovidesageneraloverviewofhowitsolvesthisproblem pattern-specificterminologyandanalogiestohelpyouunderstandtheproblemholistically thestructureofthedesignpattern,alongwithpattern-specificterminologyandanalogies otherapplication-improvingadvantages Everydesignpatternisatool-kitthataffordsthedevelopercertainadvantages.Ithinkoftheseadvantagesas“affordances”(asdiscussedinthebookTheDesignofEverydayThings).Itwasveryhelpfulformyownstudytosummarizealloftheaboveforeachdesignpattern.Herearethepoints,moreorless,thatIuse: Name/Category(Behavioral/Creational/Structural)/Summary CommonProblemScenario Terminology-Asdiscussed,patternshaveterminology,adomainthatarisesfromanalogy.It’shelpfultolayitouthere.Iuse“A”,“B”,“C”(etc)tolayouteachobjectthat’sinvolvedinthepattern.Ifindithelpfultousemethodnamesthatinclude“get”,“set”,“do”(transform,act),“read”,“write”toprovideconsistency. Addressingtheproblemofchange-TheOpen/Closedprinciplestatesthatchangeshouldbeanextension,notamodification.(example:wedon’twanttobloatAw/businesslogic,Bcanchangeandbechangedouteasily) ChangeDimensions-eachkindofchangerepresentsadimensionalaxis.Thecomplexityofapatternincreaseswiththenumberofdimensions. Scalability-Acanbe(blissfully)“ignorant”ofhowmanyB’sareaddedifAPIisconsistent.WecanaddasmanyB’s(butshouldbecognizantofperformance) Performance-ex:lazyloading Communication Couplings-Whatknowledgemustaclasshaveofworkingsofanotherclass?Manytimes,wemustupdateclassesthatcorrespondwithadimensionalchange Encapsulationanddecoupling-allowingyoutospecifycomplexinputswithminimalsystemchanges/flocking AccessControl-boundariesmakeourprogramssafer,easiertoreasonabout.SRP-thefewerjobseachcomponenthas,thebetter. Similaritiestootherpatterns Asanexample,herearetheaffordancesoftheCommandpattern: “Commandisabehavioraldesignpatternthatturnsarequestintoastand-aloneobjectthatcontainsallinformationabouttherequest.Thistransformationletsyouparameterizemethodswithdifferentrequests,delayorqueuetheexecutionofarequest,andsupportundoableoperations.” CommonProblemScenario-UIelementsbeingcoupledtowhattheydocanleadtoexplosionofsubclasses(theCartesianproblem.)Ifmultipleuseractionscantriggerinthesamerequest,weriskcodeduplication. Terminology-A-Command-arequestandrelevantinfo.A.execute()-maketherequest,A.undo().B-Invoker-thatwhichsetsandexecutesthecommand.B.setCommand(),B.executeCommand().C-Receiver-thatwhichrespondstotheexecutedcommand. Transformation-ifA.undo()isdesired,acarefulimplementationofacommandstackandabilitytorestorebackupstatesshouldbeimplemented. ChangeDimensions-AddasmanyAs,Bs,Csasneeded.BcandynamicallysetA,onlyoneatatime. Scalability-thisisscalableaslongassimultaneousrequestsdon’tburdenC. Couplings-AmustfollowaconsistentAPI Communication AccessControl-AnormallycanaccessB’smethods. Encapsulation-Bcanbeoblivioustodetailsofcommands Performance-seescalability Similarities-ChainofResponsibility,Command,MediatorandObserveraddressvariouswaysofconnectingsendersandreceiversofrequests.HandlersinChainofResponsibilitycanbeimplementedasCommands.YoucanuseCommandandMementotogetherwhenimplementing“undo”.Strategylookssimilarbut,Strategyusuallydescribesdifferentwaysofdoingthesamething,lettingyouswapthesealgorithmswithinasinglecontextclass.PrototypecanhelpwhenyouneedtosavecopiesofCommandsintohistory.YoucantreatVisitorasapowerfulversionoftheCommandpattern. DesignPatterns201:Inpractice Writecodeandtestit Myownstudyofdesignpatternsinitiallyfelthaphazard.Readabookhere,watchavideothere,comeacrossablogpostinanarticlefeed,etc.IcameacrosstheIteratorpatterninoneofthecodebasesIwasworkingon,butthathands-onexperiencedidn’ttakemetoofar.Iwantedtolearnthetopicwell,butknewthatjustconsuminginformationwasn’tenough-Ihadtoputdesignpatternsintopractice. Initially,I’dchooseadesignpattern.Thenwatchvideos,readrefactoring.guruarticles,createtheUMLdiagram,andconsumeotherresourcesuntilIfeltlikeIcouldsummarizethedesignpattern.Fromthere,I’dhopefullybeabletouseitinthefuture. ThenInoticedthathttps://refactoring.guru/design-patterns/exampleshasimplementationsofallthedesignpatternsinJava,Ruby,Go,Swift,Python,TypeScript,andmore! IsawthisasafantasticopportunitytocreateacodebasethatwouldrunallthepatternsinTypeScript.I’dhavehands-onexperiencewithTypeScriptbyhavingmadesurethecodecompiledandhavingwrittenassertionsofexpectedoutput. Theresultofthateffortishere:https://github.com/scraggo/design-patterns-refactoring-guru Irecommenddoingsomethingsimilaryourself. Step1:runningtheclientfunctionsandstudyingtheoutput.Askyourselfiftheoutputmakessense. Step2:addingtestsforthatpattern.Insteadofrelyingonconsole.log,we’dthenhaveanautomatedtestsuitethatgivesusconfidencethatallourclassmethodsworkasintended.Here’sanexamplefortheBuilderpattern: describe('withoutDirector',function(){ it('ConcreteBuilder1callsreset()aftergetProduct()',function(){ builder.producePartA(); constproduct=builder.getProduct(); expect(product).to.deep.equal({ parts:['PartA1'], }); expect(builder.getProduct()).to.deep.equal({ parts:[], }); }); Wehaveanexplicittestforexactlywhattheitblockdescribes:“ConcreteBuilder1callsreset()aftergetProduct()’“.We’reabletogeta“product”andassertthatit’scorrect.Afterwegetit,wecallreset()whichclearsouttheproductpartsandweassertthatit’sanemptyarray. https://github.com/scraggo/design-patterns-refactoring-guruisopensourceifyou’dliketocontributetestsforayet-to-be-testedpattern. Studydesignpatternsinthewild Asmentionedinmyintroductiontodesignpatterns,therearemanylibrariesthatyoumayinteractwiththatutilizedesignpatternsinternallyandallowdeveloperstotakeadvantageofthem.Someexamples: SubscriptionmethodsinReduxuseapub-subObserversystem ReactlifecyclemethodsandDatabasehooks(seetheSequelizeORMforexample)utilizetheTemplateMethodpattern https://github.com/davidkpiano/xstateisastatemachine-Statepattern YoucanusetheDecoratorpatterndirectlyinJavaScriptifyouconfigureyourapplicationusingexperimentaltooling.Here’sanexampleinReact.HigherOrderComponents(HOCs)achieveasimilareffectwithfunctioncomposition.ReadaboutthemintheofficialReactdocsandhere. AsyoulearntheinternalsofJavaScriptsystemslikeReact,Redux,Gulp,Webpack,databasesystems,etc,beonthelookoutformentionsofarchitecture.Findthecode(ifit’sopensource)andseehowtheauthor(s)implementedthecode. Asforsomesimplerexamplesbuiltfortutorialpurposes: Python: https://miguendes.me/design-patterns-that-make-sense-in-python-simple-factory https://github.com/faif/python-patterns DesignPatterns301:Advanced “Solution-first”thinking;insearchofaproblem Nowthatwe’vebuiltuptheoreticalandpracticalunderstandingofthepatterns,wecansetourselvesuptosolvefutureproblemsbygivingourselvessomecreativeexercises. Asstatedbefore:“Tobreaknewground,wemightopttogo“backwards”byseekingproblemswithasolutioninmind,reversingtheusualproblem-firstroutine.Thisallowsustosolveproblemsinanewwayandreinforceourproblem-solvingschemas.” Thisworksbyforcingustoconjureabunchofproblems-gettingourcreativejuicesflowing.Doesanapplicationyouuse,sayVictorOps,remindyouoftheObserverpattern?Great-trytocreateyourownhigh-levelversionofthatserviceusingthepatterntosolvetheproblem. Onceyou’vegotthehangofonepattern,trycombiningtwodesignpatterns.Youcansolvenewproblemsthisway.Systematicallycombiningpatternsandsimultaneouslythinkingofapplicationsforthemwillbeimmenselybeneficial. Thiswasasuggestionfrommymentorwhichweranwith.Iaddedanumberofcombinationstothecombinations/directoryinhttps://github.com/scraggo/design-patterns-refactoring-guru: CompositeandObserver-Anotificationsystemthatselectivelynotifiedthesubscriberbasedontheevent FactoryandStrategy-Agenericproductdatawasretrievedbyastrategyandcoupledaccordinglyinafactory IteratorandVisitor-AllowsJSONandHTMLexportofawordcollectionstoredinanarbitrarycollectiontype AbstractFactoryandBridge-Adigitalaudioworkstationthatinitializesatrackwithaninstrumentcollection FlyweightandMemento-Aslidesappthatcachestheimagesandhasanundo/redohistory Resources Finally,hereareanumberofresourcesthatI’vefoundhelpfulwhilelearning: refactoring.guru DiveintoDesignPatternsbyAlexanderShvets DesignPatterns:ElementsofReusableObject-OrientedSoftware ChristoperOkhravivideoplaylist https://codesource.io/javascript-design-patterns/ https://blog.logrocket.com/design-patterns-in-node-js/ https://khalilstemmler.com/articles/solid-principles/solid-typescript/ https://www.google.com/amp/s/stackify.com/interface-segregation-principle/amp/ https://levelup.gitconnected.com/design-patterns-in-modern-javascript-development-ec84d8be06ca https://medium.com/@andy.sek94/s-o-l-i-d-principles-for-software-development-611b5f7170de https://miguendes.me/design-patterns-that-make-sense-in-python-simple-factory https://github.com/faif/python-patterns https://docs.microsoft.com/en-us/azure/architecture/patterns/ MyintroductiontoDesignPatterns Iintroducedesignpatternsanddiscussthe“what”andthe“why”ofthemhere.←IntroductiontoDesignPatterns:Whythey'reworthlearningProgrammingwithmoreease→
延伸文章資訊
- 1Design Patterns - Refactoring.Guru
Design Patterns are typical solutions to commonly occurring problems in software design. They are...
- 2Design Patterns & Refactoring
Hello, world! I'm SourceMaking. I will tell you a lot of stories about good software architecture...
- 3Refactoring.Guru - GitHub
Guru has 12 repositories available. Follow their code on GitHub. ... design-patterns-typescript P...
- 4Gang of Four Design Patterns - Spring Framework Guru
The GoF Design Patterns are broken into three categories: Creational Patterns for the creation of...
- 5Introduction to Design Patterns: Why they're worth learning
the writings of Alexander Shvets on refactoring.guru. The author has created an amazing resource ...