Head First Design Patterns using Go - FAUN Publication

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

Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during ... Signin🎙️‎‎‎‎‎‎Podcast✍️Write4FAUN‎📰‎‎‎‎‎CloudNativeNews‎🗣️‎‎‎‎‎‎Slack🖤SponsorFAUNHeadFirstDesignPatternsusingGo—1.WelcometoDesignPatterns:theStrategyPatternAdescriptiveseriesonthedesignpatternsbasedontheO’ReilybookofthesamenameadaptedtoGofromJavaPiyushSinhaFollowMay3·6minreadTableofContents0.IntroductionWelcometoDesignPatterns:theStrategyPatternKeepingyourObjectsintheknow:theObserverPatternDecoratingObjects:theDecoratorPatternBakingwithOOgoodness:theFactoryPatternEncapsulatingInvocation:theCommandPatternBeingAdaptive:theAdapterandFacadePatternsEncapsulatingAlgorithms:theTemplateMethodPatternWell-managedCollections:theIteratorandCompositePatternsTheStateofThings:theStatePatternControllingObjectAccess:theProxyPatternPatternsofPatterns:CompoundPatternsThisseriesofarticleswillrunyoubythedesignpatternsthewayitisexplainedintheHeadFirstDesignPatternsbookusingGoasthecodinglanguage.ProblemStatement1:Developagame,SimUDuckappwhichshowsalargevarietyofduckspeciesswimmingandmakingquackingsounds.Solution:StandardOOtechniquesandcreatedoneDucksuperclassfromwhichallotherducktypesinherit.ProblemStatement2:DucksneedtoFLY.Solution:Addafly()methodintheDuckclassandthenalltheduckswillinheritit.ProblemStatement3:RubberDuckiesareflyingaroundthescreen.NotallsubclassesofDuckhavetheflyingbehaviour.Neitherdoallquack.Whatwasthoughtasagreatuseofinheritanceforthepurposeofreusehasn’tturnedoutsowellwhenitcomestomaintenance.Solution:Overridethefly()andquack()methodsintheRubberDuckclass.ProblemStatement4:Whathappenswhenweaddwoodendecoyducks?Theydon’tflyorquack.Runtimebehaviourchangesaredifficult.Hardtogainknowledgeofallduckbehaviours.Changescanunintentionallyaffectotherducks.Solution:BringinInterface:takethefly()behaviouroutoftheDucksuperclassmakeaFlyable()interfacewithafly()method.Thatway,onlytheducksthataresupposedtoflywillimplementthatinterfaceandhaveafly()methodSamegoesforquack()behaviourProblemStatement5:Codeisduplicatedacrosssubclasses—maintenancenightmare.Therecanbemorethanonekindofflyingbehaviourevenamongtheducksthatdofly.Solution:DesignPrinciple1:Identifytheaspectsofyourapplicationthatvaryandseparatethemfromwhatstaysthesame.Takewhatvariesand“encapsulate”itsoitwon’taffecttherestofyourcode.Result?FewerunintendedconsequencesfromcodechangesandmoreflexibilityinyoursystemsLookingattheDuckclass,otherthanproblemswithfly()andquack(),itisworkingwellandtherearenootherpartsthatappeartovaryorchangefrequently.ToseparatethesebehavioursfromtheDuckclass,we’llpullbothmethodsoutoftheDuckclassandcreateanewsetofclassestorepresenteachbehaviour.Forinstance,wemighthaveoneclassthatimplementsquacking,anotherthatimplementssqueaking,andanotherthatimplementssilenceDesignPrinciple2:Programtoaninterface,notanimplementation.TheDucksubclasseswilluseabehaviourrepresentedbyaninterface(FlyBehaviourandQuackBehaviour),sothattheactualimplementationofthebehaviour(inotherwords,thespecificconcretebehaviourcodedintheclassthatimplementstheFlyBehaviourorQuackBehaviour)won’tbelockedintotheDucksubclass.Thatway,theDuckclasseswon’tneedtoknowanyoftheimplementationdetailsfortheirownbehaviours.Benefitsofthisdesign:a)codereusability,b)newbehaviourscanbeaddedwithoutmodifyinganyofourexistingbehaviourclassesortouchinganyoftheDuckclassesFinalUMLDiagramDesignPrinciple3:Favourcomposition(HAS-Arelationship)overinheritance(IS-Arelationship)Givesmoreflexibility,canchangebehaviour/algorithmatruntimeCongratulationsonlearningthefirstdesignpattern:theSTRATEGYpatternWikiDefinition:TheStrategyPatterndefinesafamilyofalgorithms,encapsulateseachone,andmakestheminterchangeable.Strategyletsthealgorithmvaryindependentlyfromclientsthatuseit.Showmethecode:FlyBehavioursetofclassespackagemainimport"fmt"/***Interfacethatallflyingbehaviourclassesimplement*/typeflyBehaviourinterface{fly()}/***Flyingbehaviourimplementationforducksthatfly*/typeflyWithWingsstruct{}func(fw*flyWithWings)fly(){fmt.Println("I'mflying")}/***Flyingbehaviourimplementationforducks*thatdonotfly(likerubberanddecoyducks)*/typeflyNoWaystruct{}func(fnw*flyNoWay)fly(){fmt.Println("Ican'tfly")}QuackBehavioursetofclassespackagemainimport"fmt"typequackBehaviourinterface{quack()}typequackstruct{}func(q*quack)quack(){fmt.Println("Quack")}typemuteQuackstruct{}func(mq*muteQuack)quack(){fmt.Println("Silence")}typesqueakstruct{}func(s*squeak)quack(){fmt.Println("Squeak")}DuckAbstractClassReferthistoknowhowtoimplementAbstractClassesinGopackagemainimport"fmt"typeabstractDuckstruct{displayfunc()/***Declaretworeferencevariablesforthebehaviourinterfacetypes.*Allducksubclassesinheritthese*/flyingBehaviourflyBehaviourquackingBehaviourquackBehaviour}/***Delegateflyandquackbehaviourto*respectivebehaviourclasses*/func(d*abstractDuck)performFly(){d.flyingBehaviour.fly()}func(d*abstractDuck)performQuack(){d.quackingBehaviour.quack()}func(d*abstractDuck)swim(){fmt.Println("Allducksfloat,evendecoys!")}/***Settingthebehaviourdynamically*/func(d*abstractDuck)setFlyingBehaviour(fbflyBehaviour){d.flyingBehaviour=fb}func(d*abstractDuck)setQuackingBehaviour(qbquackBehaviour){d.quackingBehaviour=qb}IntegratingwithDucksubclassestypemallardDuckstruct{*abstractDuck}funcnewMallardDuck()*mallardDuck{//implementingtheabstractmethodd:=&abstractDuck{display:func(){fmt.Println("I’marealMallardduck")},flyingBehaviour:&flyWithWings{},quackingBehaviour:&quack{},}return&mallardDuck{d}}typemodelDuckstruct{*abstractDuck}funcnewModelDuck()*modelDuck{//implementingtheabstractmethodd:=&abstractDuck{display:func(){fmt.Println("I’marealModelduck")},flyingBehaviour:&flyNoWay{},quackingBehaviour:&muteQuack{},}return&modelDuck{d}}TestingtheDuckCodepackagemainfuncmain(){mallardDuck:=newMallardDuck()mallardDuck.display()mallardDuck.performFly()mallardDuck.performQuack()mallardDuck.swim()modelDuck:=newModelDuck()modelDuck.display()modelDuck.performFly()modelDuck.performQuack()modelDuck.swim()}Runthecode!I’marealMallardduckI'mflyingQuackAllducksfloat,evendecoys!I’marealModelduckIcan'tflySilenceAllducksfloat,evendecoys!CreatingnewFlyBehaviour/***Rocket-poweredflyingbehaviour*/typeflyRocketPoweredstruct{}func(frp*flyRocketPowered)fly(){fmt.Println("I’mflyingwitharocket!")}Changingbehaviourdynamicallypackagemainimport"fmt"funcmain(){mallardDuck:=newMallardDuck()mallardDuck.display()mallardDuck.performFly()mallardDuck.performQuack()mallardDuck.swim()modelDuck:=newModelDuck()modelDuck.display()modelDuck.performFly()modelDuck.performQuack()modelDuck.swim()modelDuck.setFlyingBehaviour(&flyRocketPowered{})fmt.Print("NewFlyingBehaviourofModelDuck:")modelDuck.performFly()}Runit!I’marealMallardduckI'mflyingQuackAllducksfloat,evendecoys!I’marealModelduckIcan'tflySilenceAllducksfloat,evendecoys!NewFlyingBehaviourofModelDuck:I’mflyingwitharocket!BIGPICTUREUsetheStrategypatternwhenyouwanttousedifferentvariantsofanalgorithmwithinanobjectandbeabletoswitchfromonealgorithmtoanotherduringruntime.UsetheStrategywhenyouhavealotofsimilarclassesthatonlydifferinthewaytheyexecutesomebehaviour.Usethepatternwhenyourclasshasamassiveconditionaloperatorthatswitchesbetweendifferentvariantsofthesamealgorithm.Next:KeepingyourObjectsintheknow:theObserverPatternSourceCode:https://github.com/pi-sin/head-first-design-patterns-in-golangJoinFAUN:Website💻|Podcast🎙️|Twitter🐦|Facebook👥|Instagram📷|FacebookGroup🗣️|LinkedinGroup💬|Slack📱|CloudNativeNews📰|More.Ifthispostwashelpful,pleaseclicktheclap👏buttonbelowafewtimestoshowyoursupportfortheauthor👇FAUNPublicationTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiastsFollow40ProgrammingDesignPatternsGolangSoftwareDevelopmentObjectOriented40 claps40WrittenbyPiyushSinhaFollowEngineeringleader@Myntra(India’slargestFashione-store)|Ex-Flipkart|5AMClubMember|Searchingformynextadventure.FollowFAUNPublicationFollowTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiasts.Medium’slargestDevOpspublication.FollowWrittenbyPiyushSinhaFollowEngineeringleader@Myntra(India’slargestFashione-store)|Ex-Flipkart|5AMClubMember|Searchingformynextadventure.FAUNPublicationFollowTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiasts.Medium’slargestDevOpspublication.MoreFromMediumThestartofajourneymichaelthomasTrelloAPItestingwithPostman,CircleCIGururajHm7thingsaboutRubyonRailsthatmakeitunique.RailsCarmaBuilderDesignPattern — C#BugraSitemkarX-Cartvs3dCart:Whichoneshouldyouchoose?LitExtensionSTEMBoxupdate#17 — WorkinghardonByteBoi’ssoftwareandhardwareAlbertGajšakinCircuitMessQueue:Thread_safeFIFOImplementationCherimaMomininAIPerceptronHowtosetupsimpleimageuploadwithNodeandAWSS3FilipJergainWe’vemovedtofreeCodeCamp.org/news



請為這篇文章評分?