Prototype Design Pattern inGolang - FAUN Publication
文章推薦指數: 80 %
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,tounderstandhowapplicablethisareaofknowledgeisintheworldoftheGolanglanguage.Wehavealreadylookedatpatterns:SimpleFactory,Singleton,andStrategy.TodayIwanttoconsideranotherdesignpattern—Prototype.Whatisitneededfor?Itisacreatingdesignpatternthatallowsobjectstobecopiedwithoutgoingintothedetailsoftheirimplementation.Whatproblemdoesitsolve?Imagineyouhaveanobjectthatneedstobecopied.Howtodoit?Createanemptyobjectofthesameclass,thencopythevaluesofallfieldsfromtheoldobjecttothenewonebyone.Fine,butthereisanuance!Noteveryobjectcanbecopiedinthisway,becausepartofitsstatecanbeprivate,whichmeansitisinaccessibletotherestoftheprogramcode.Thereisanotherproblemaswell.Thecopyingcodewillbecomedependentontheclassesofthecopiedobjects.Afterall,inordertoiterateoverallthefieldsofanobject,youneedtobindtoitsclass.Becauseofthis,youwon’tbeabletocopyobjectsknowingonlytheirinterfacesandnotspecificclasses.What’sthesolution?ThePrototypepatterninstructsthecopyingobjectsthemselvestomakecopies.Itintroducesacommoninterfaceforallobjectsthatsupportcloning.Thisallowsobjectstobecopiedwithoutbeingboundtotheirspecificclasses.Typicallysuchaninterfacehasonlyoneclonemethod.Theimplementationofthismethodindifferentclassesisverysimilar.Themethodcreatesanewobjectofthecurrentclassandcopiesthevaluesofallfieldsofitsownobjectintoit.Evenprivatefieldscanbecopiedthiswaysincemostprogramminglanguagesallowaccesstoprivatefieldsofanyobjectofthecurrentclass.Theobjectbeingcopiediscalledtheprototype,hencethenameofthepattern.Whenprogramobjectscontainhundredsoffieldsandthousandsofpossibleconfigurations,prototypescanserveasanalternativetosubclassing.Theprototypepatternshouldcopyobjectsofanycomplexitywithoutbindingtotheirspecificclasses.Allprototypeclassesshareacommoninterface.Therefore,youcancopyobjectsregardlessoftheirspecifictypesandalwaysbesuretogetanexactcopy.Cloningisdonebytheprototypeobjectitself,whichallowsittocopythevaluesofallfields,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-orientedlanguagesarealientoit.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
延伸文章資訊
- 1what is the difference between pool and prototype patterns?
I've just read the chapter on Creational patterns in the book Design Patterns in golang. These ar...
- 2golang-design-pattern/prototype.go at master - GitHub
设计模式Golang实现-《研磨设计模式》读书笔记. Contribute to senghoo/golang-design-pattern development by creating an...
- 3Prototype Design Pattern inGolang - FAUN Publication
The Prototype pattern instructs the copying objects themselves to make copies. It introduces a co...
- 4一起幫忙解決難題,拯救IT 人的一天
【Day 27】Design Patterns with Go II:Prototype, Singleton, Facade ... 程式碼都來自golang-design-pattern,註...
- 5Prototype Design Pattern in Golang - Smartscribs
Prototype Design pattern is a creational design pattern that is used to create a copy of objects ...