How to Learn Design Patterns | scraggo.com

文章推薦指數: 80 %
投票人數:10人

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→



請為這篇文章評分?