Prototype Design Pattern in Golang - Smartscribs
文章推薦指數: 80 %
Prototype Design pattern is a creational design pattern that is used to create a copy of objects while keeping the performance in mind. It ... PrototypeDesignPatterninGolangPublishedbyShubhamonMarch18,2020March18,2020 Inthisseries,wearediscussingDesignPatterns.Inthepreviousarticles,wehavealreadydiscussedtheObjectFactoryDesignPattern, SingletonDesignPattern.andBuilderDesignPattern.Afteralongbreakofaboutamonth,wearebackagaintoexploreandimplementthePrototypeDesignPatterninGolang. PrototypeDesignpatternisa creationaldesignpatternthatisusedtocreateacopyofobjectswhilekeepingtheperformanceinmind.Itspecifiesthekindofobjectstocreateusingprototypicalinstanceandcreatesnewobjectsbycopyingthisprototype. Confusedbytheabovestatement?Letusgoeasy.Pleasenotethatsometimesobjectcreationisacostlyjob.Forexample,ifyoufetcharowfromDatabaseandkeepitasaDAO,itisacostlyaffair.Thegeneralideaoftheprototypedesignpatternishavingasetofobjects(orevenanobject)thatarecreatedatcompile-time,butyouarefreetocreateanynumberofcopiesatruntime.Wejustmutatetheoriginalobjectandsaveittoanewobject.Itsavesusfromrepetitiveobjectcreation. Letusgobacktothedatabaseexample.Wefetchacolumn,andkeepitasaDAO.Nowforeveryfield,wewanttoupdate,wejustmutatetheDAO,insteadofcallingthedatabaseeverytime. Letustakeonemoreexample,Supposeyouhaveanobjectwithalargenumberoffieldsandyouhavetocreateaclone.Thesimplesolutionistoinstantiateanemptyobjectofthesametype,andtheniterateoverallthefieldsandcopyeachfieldfromtheoriginalobjecttotheclonedobject. Apartfrombeingatiringprocess,thereisonemorecatch,sometimesyoujustknowtheinterfaceandnottheexactstructthatisgiventoyou.Undersuchscenariosdeterminingtheexactstructthatisimplementingtheinterfaceandinstantiateanobjectofthattypeinruntimecanbeatediousjob. Allthesetinyproblemsareeasilysolvedwiththehelpofaprototypedesignpattern.Butbeforewebegin,letusunderstandtheterminology: Prototype:Itdeclaresaninterfaceforcloningitself. ConcretePrototype: Itimplementsanoperationforcloningitself. Client:Createsanewobjectbyaskingtheprototypetocloneitself. Implementation WeusethisPrototypeDesignPatterninGolangwhenwewanttocustomizehowanobjectiscloned.Letusseetwoexamplesofcateringtodifferentsituations. Forthefirstscenario,letusbuildautilitythatgivesusadifferentkindofuserobjectasperourneeds.Tobeginwithwehaveastructuserthathasemailandmobileasit’stwoproperties.Wewanttomutatetheobject,withoutaffectingitsoriginalinstance.Thegoalofthiswholeutilityistogeneratedifferentuserobjectswithoutlosingtheflexibilityofcustomizingthemwithoutchangingtheinitialobject.Insimplewords,itisautilitythatcreatesnewuserobject,withthedesiredchanges,justbycopyinganinitialobjectandthenchangingthefieldsofthecopiedobjects,leavingtheoriginalobjectunchanged. packageprototype typeUserstruct{ emailstring mobilestring } funcNewUser(emailstring,mobilestring)User{ returnUser{ email:email, mobile:mobile, } } //WithEmailcreatesacopyofUserwiththeprovidedemail func(uUser)WithEmail(emailstring)User{ u.email=email returnu } //WithPhonecreatesacopyofUserwiththeprovidedphone func(uUser)WithMobile(mobilestring)User{ u.mobile=mobile returnu } Ifyouobserveclosely,youwillfindthewecallthefunctionsWithEmailandWithUser fromUser(andnot*User).Thus,atthetimewhenthefunctionsarecalled,anewcopyoftheuserobjectismadeandpassedtothefunctions,andallthemutationshappentothecopiedobject.Thisallmayseemnotworththeeffortrightnow,butjustimaginehowusefulitbecomeswhentheobjectinstantiationisacostlyaffair.Inthisutilityweneverinstantiateanobject,wejustcopyanalreadyinstantiatedobjectandmutateisasperourneeds. Nowletuslookattheothercase(whichisinspiredfromhere),thecaseinwhichwearegivenaninterfaceandwedon’texactlyknowwhichstructissatisfyingthatinterface.Letustrydevelopinganobjectmimickingfilesystem. Anyfilesystemhasfilesandfoldersandfoldersitselfcontainfilesandfolders.Eachfile and foldercanberepresentedbya nodeinterface. node interfacealsohasthe clone()function. packagemain typenodeinterface{ print(string) clone()node } Nowletusdefinethetwotypeofentities,filesandfolders. packagemain importfmt typefilestruct{ namestring } func(f*file)print(indstring){ fmt.Println(ind+f.name+"_clone") } func(f*file)clone()node{ return&file{name:f.name} } packagemain import"fmt" typefolderstruct{ children[]node namestring } func(f*folder)print(indentationstring){ fmt.Println(indentation+f.name+"_clone) for_,i:=rangef.childrens{ i.print(indentation+indentation) } } func(f*folder)clone()node{ cloneFolder:=&folder{name:f.name} vartempChildrens[]node for_,i:=rangef.childrens{ copy:=i.clone() tempChildrens=append(tempChildrens,copy) } cloneFolder.childrens=tempChildrens returncloneFolder } Sincebothfileandfolderstructimplementstheprintandclonefunctions,hencetheyareoftypeinode.Also,noticetheclonefunctioninbothfileandfolder.Theclonefunctioninbothofthemreturnsacopyoftherespectivefileorfolder.Whilecloningweappendthekeyword“_clone”forthenamefield.Let’swritethemainfunctiontotestthingsout. packagemain import"fmt" funcmain(){ file1:=&file{name:"File1"} file2:=&file{name:"File2"} file3:=&file{name:"File3"} folder1:=&folder{ childrens:[]inode{file1}, name:"Folder1", } folder2:=&folder{ childrens:[]inode{folder1,file2,file3}, name:"Folder2", } fmt.Println("\nPrintinghierarchyforFolder2") folder2.print("") cloneFolder:=folder2.clone() fmt.Println("\nPrintinghierarchyforcloneFolder") cloneFolder.print("") } HereweseehowwecouldcloneaninterfacewithoutknowingtheunderlyingtypeusingthePrototypedesignpatterninGolang. Golanghasaninbuiltmechanismofcloningobjects,andthusyouwouldnotfindalotofusesofthisparticulardesignpattern.However,ifyouwishtoknowaboutthedesignpatterns,thisisjustonemoreflavour. Categories: DesignPatternsGolangTech Tags:DesignPatternsDesignPatternsGolangSystemDesign 0Comments LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Name* Email* Website What'sonyourmind?Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. Whatareyoulookingfor? Searchfor: TagsAPI Architecture arrowfunction async AWS BASH Cache Caching CircuitBreakers Console Customization Debugging DesignPatterns DesignPatterns Destructuring devops DistributedCache DistributedComputing es6 get Golang Hashing HTTP JavaScript Linux map NodeJS post Prompt ReactNative reduce REST rpc Server Servers Shell ShellScripting Singleton SOAP SpreadOperator SpreadSyntax StructuralDesignPattern SystemDesign Terminal WEB Categories AWS(6) DesignPatterns(7) Devops(3) Golang(14) JavaScript(14) linux(4) PersonalFinance(1) ReactNative(2) SystemDesign(8) Tech(37) RelatedPosts Golang DataStreamsinGolang Asaprogrammer,youwilloftenneedtoprocessdatathatisbeencontinuouslyproducedbyoneormoresources.Forexample,youmightneedtoprocesslogsgeneratedbyarunningsystem.DatahereReadmore… JavaScript DailyReactHacks Sometimesyouaretoolazytoconnectthedebugger.Someusingreduxdevtoolstomonitorthestateseemslikeadauntingtask.Andthesearethescenarioswherehackscomeintothepicture.HereReadmore… JavaScript MapandObjectinJavascript. Recently,whiledevelopinganapplicationformystartupinReactNative,Iencounteredastrangeissue.Myfirebasequerywasgivingasortedresult,whichIwasstoringinanObject.ButwhileretrievingtheReadmore…
延伸文章資訊
- 1golang-design-pattern/prototype.go at master - GitHub
设计模式Golang实现-《研磨设计模式》读书笔记. Contribute to senghoo/golang-design-pattern development by creating an...
- 2Golang design pattern 05 - prototype pattern
Golang design pattern 05 - prototype pattern. 2021-09-19 06:28:16 by Robin Zhang. The prototype p...
- 3Prototype Design Pattern inGolang - Morioh
The Prototype pattern instructs the copying objects themselves to make copies. ... The articles o...
- 4一起幫忙解決難題,拯救IT 人的一天
【Day 27】Design Patterns with Go II:Prototype, Singleton, Facade ... 程式碼都來自golang-design-pattern,註...
- 5Prototype Pattern in Go (Golang)
It is a creational design pattern that lets you create copies of objects. In this pattern, the re...