Prototype Design Pattern inGolang - FAUN Publication

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

The Prototype pattern instructs the copying objects themselves to make copies. It introduces a common interface for all objects that support ... Signin🎙️‎‎‎‎‎‎Podcast✍️Write4FAUN‎📰‎‎‎‎‎CloudNativeNews‎🗣️‎‎‎‎‎‎Slack🖤SponsorFAUNPrototypeDesignPatterninGolangAlexVersusFollowMay24·6minreadHifriends!Withyou,AlexandIcontinueourseriesofarticlesontheuseofdesignpatternsintheGolanglanguage.Itisinterestingtoreceivefeedbackfromyou,tounderstandhowapplicablethisareaof​​knowledgeisintheworldoftheGolanglanguage.Wehavealreadylookedatpatterns:SimpleFactory,Singleton,andStrategy.TodayIwanttoconsideranotherdesignpattern—Prototype.Whatisitneededfor?Itisacreatingdesignpatternthatallowsobjectstobecopiedwithoutgoingintothedetailsoftheirimplementation.Whatproblemdoesitsolve?Imagineyouhaveanobjectthatneedstobecopied.Howtodoit?Createanemptyobjectofthesameclass,thencopythevalues​​ofallfieldsfromtheoldobjecttothenewonebyone.Fine,butthereisanuance!Noteveryobjectcanbecopiedinthisway,becausepartofitsstatecanbeprivate,whichmeansitisinaccessibletotherestoftheprogramcode.Thereisanotherproblemaswell.Thecopyingcodewillbecomedependentontheclassesofthecopiedobjects.Afterall,inordertoiterateoverallthefieldsofanobject,youneedtobindtoitsclass.Becauseofthis,youwon’tbeabletocopyobjectsknowingonlytheirinterfacesandnotspecificclasses.What’sthesolution?ThePrototypepatterninstructsthecopyingobjectsthemselvestomakecopies.Itintroducesacommoninterfaceforallobjectsthatsupportcloning.Thisallowsobjectstobecopiedwithoutbeingboundtotheirspecificclasses.Typicallysuchaninterfacehasonlyoneclonemethod.Theimplementationofthismethodindifferentclassesisverysimilar.Themethodcreatesanewobjectofthecurrentclassandcopiesthevalues​​ofallfieldsofitsownobjectintoit.Evenprivatefieldscanbecopiedthiswaysincemostprogramminglanguages​​allowaccesstoprivatefieldsofanyobjectofthecurrentclass.Theobjectbeingcopiediscalledtheprototype,hencethenameofthepattern.Whenprogramobjectscontainhundredsoffieldsandthousandsofpossibleconfigurations,prototypescanserveasanalternativetosubclassing.Theprototypepatternshouldcopyobjectsofanycomplexitywithoutbindingtotheirspecificclasses.Allprototypeclassesshareacommoninterface.Therefore,youcancopyobjectsregardlessoftheirspecifictypesandalwaysbesuretogetanexactcopy.Cloningisdonebytheprototypeobjectitself,whichallowsittocopythevalues​​ofallfields,evenprivateones.Inthiscase,allpossibleprototypesareprocuredandconfiguredatthestageofprograminitialization.Then,whentheprogramneedsanewobject,itcreatesacopyfromthepreparedprototype.ClassdiagramPrototypeClassDiagramInthediagram,weseetheprototypeinterface,whichdescribescloningoperations.Inmostcases,thisistheonlyclonemethod.Aconcreteprototypeimplementsthelogicofcloningitself.Itisimportanttoavoidthecloningerrorhere.Forexample,cloningrelatedobjects,untanglingrecursivedependencies,andmore.Theclientcreatesacopyoftheobjectbyaccessingitthroughthegenericprototypinginterface.It’ssimple.Howtoimplement?Adetailedstep-by-stepimplementationofthispattern,aswellasotherdesignpatternsinPHP,canbefoundhere.OurtaskistoimplementthePrototypepatternintheGolanglanguage.Let’sconsideranexampleoftheimplementationofaproductcatalogrubricatorinanonlinestorewithalargenumberofproductcategories.Therubricatorhastop-levelsectionsthatcontainfinalrubricsandsecond-levelsections.Second-levelsectionscanalsocontainheadingsandthird-levelsections,etc.Thatis,itisatree-likestructureofobjects,theyhavetrunksandleaves—thefinalelementsofthetree.Eachheadingandsectionhasitsownsetofpropertiesinrelationtothesection’sproducts.Forexample,shirtsarecolor,size,brand,etc.Atsomepoint,ittooktheadminpaneloftherubricatortocopythesectionsintothesectionandtherubricswithallthepropertiesofthegoods.Forexample,intheclothingsection,youneedtoquicklybeabletoclonetheheadingsformen,women,children’sshorts,etc.Eachcategory,asafinalelementoftherubricator,canberepresentedbytheprototypeinterface,whichdeclarestheclonefunction.Asabasisfortheconcreteprototypesoftherubricandsection,wetakethestructtype,whichimplementtheshowandclonefunctionsoftheprototypeinterface.So,let’simplementtheprototypeinterface.Next,we’llimplementaconcreteprototypedirectorythatimplementstheprototypeinterfacerepresentingtherubricatorsection.Andaspecificprototypefortherubric.Bothstructuresimplementtwofunctionsshow,whichisresponsiblefordisplayingthespecificcontentofthenodeandcloneforcopyingthecurrentobject.Theclonefunctiontakesasitsonlyparameteranargumentthatreferstothetypeofthepointertothestructureofaparticularprototype—thisiseitheracategoryoradirectory.Anditreturnsapointertothestructurefield,adding_clonetothefieldname.Intheclient,wecreateatree-likestructureoftherubricator.Copyoneofthedirectorieswithallchildren.Weseethattheentiretreehasbeensuccessfullycopiedthankstotheimplementationofthecloningfunctionforeachspecificprototype.Output:Opendirectory2Directory2Directory1category1category2category3Cloneandopendirectory2Directory2_cloneDirectory1_clonecategory1_clonecategory2_clonecategory3_cloneWhentoapply?Youhavemanyobjectswithmanypropertiesandneedtocreateclonesquicklyandefficiently.Thepatternsuggestsusingasetofprototypesinsteadofsubclassingtodescribepopularobjectconfigurations.Insteadofsubclassingobjects,youcopyexistingprototypeobjectsthatalreadyhavestatesetup.Thus,avoidinganincreaseinthenumberofclassesintheprogramandreducingitscomplexity.Thecodeshouldnotdependontheclassesofthecopiedobjects.Ifyourcodeworkswithobjectspassedthroughacommoninterface,youcannotbindtotheirclasses,evenifyouwantedto,sincetheirspecificclassesareunknown.Theprototypeprovidestheclientwithacommoninterfaceforworkingwithallprototypes.Theclientdoesnotneedtodependontheclassesofthecopiedobjects,butonlyonthecloninginterface.SummarizeFriends,thePrototypepatternoffers:Ahandyconceptformakingcopiesofobjects.Helpstoavoidadditionalefforttocreateanobjectinastandardway,whenitisprohibitivelyexpensivefortheapplication.Inobjectlanguages,itallowsyoutoavoidinheritingthecreatorofanobjectintheclientapplication,astheabstractfactorypatterndoes,forexample.Bytheway,friends,hereyoucanseetheresultsofasurveyofHabrreaders.63%ofthosesurveyedbelievethatusingdesignpatternsinGolangisevil.Mostlikely,itisconnectedwiththefactthattheGolanglanguageisproceduralandapproachesofobject-orientedlanguages​​arealientoit.Butitisworthconsideringtheimplementationandapplicationoftemplates,sincethisallowsyoutounderstandthemmoreandperiodicallyapplythemtosolvecertainproblems.Eachapproachrequires,ofcourse,discussionandjudiciousapplication.Friends,Iwasgladtosharethetopic,Alex.Goodluck!JoinFAUN:Website💻|Podcast🎙️|Twitter🐦|Facebook👥|Instagram📷|FacebookGroup🗣️|LinkedinGroup💬|Slack📱|CloudNativeNews📰|More.Ifthispostwashelpful,pleaseclicktheclap👏buttonbelowafewtimestoshowyoursupportfortheauthor👇FAUNPublicationTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiastsFollow16GolangPHPDesignPatternsPhpDevelopersGo16 claps16WrittenbyAlexVersusFollowFollowFAUNPublicationFollowTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiasts.Medium’slargestDevOpspublication.FollowWrittenbyAlexVersusFollowFAUNPublicationFollowTheMust-ReadPublicationforCreativeDevelopers&DevOpsEnthusiasts.Medium’slargestDevOpspublication.MoreFromMediumOpen-SourceinEverydayLifeAnishDeinJavaScriptinPlainEnglishPostgresonMacwithBrew💻GopiKrishnaKancharlainThinkSpecial — GopiKKancharlaSabioCodingBootcampvs.UCICodingBootcampSabioCodingBootcampinSabioCodingBootcampLearningGo — Arrays&slicesPrateekGuptainNerdForTechBudgetingforanAppDevelopmentProjectKumulosLearningSQLwithDunderMifflinJulianaAlmeidaInstallgolangfromcommandlineDrakeEvansTestnetEpisode3iscoming!MassaLabs



請為這篇文章評分?