Prototype Design Pattern in Golang - Smartscribs

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

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…



請為這篇文章評分?