Object Factory Design Pattern in Golang - Smartscribs

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

Please note the manager is opaque to all the details of how a science student is called. This in some ways is the use-case of the object factory ... ObjectFactoryDesignPatterninGolangPublishedbyShubhamonDecember11,2019 Inthepreviousarticle,wediscussedabouttheSingletondesignpatternanditssampleusage.Inthisarticle,wewilldiscussonemore,ObjectFactoryDesignPatterninGolang.ObjectFactoryisthemostprobablymostuseddesignpatternintheOOPworld.Itdealswithinstantiationandcreationofobjectsandhenceisapartofthecreationaldesignpattern.ThisdesignpatternwasintroducedtousinthefamousbookDesignPatterns:ElementsofReusableObject-OrientedSoftwarebyErichGamma,RichardHelm,RalphJohnson,andJohnVlissides. InFactoryPattern,wecancreatetheobjectwithoutexposingthelogicoftheclientthatiscreatingtheobject.Itisliketheend-userasksforacertainkindofobjectanditisgiventohim,abstractingalltheexplanationastohowtheobjectwasobtained,etc.Letustakeanexampletohelpusunderstanditbetter.Letussupposethereisaschoolwhichhasthreestreams:Science,Arts,andCommerce.OnefinedaythemanageroftheschoolcomesandwishestotalktoastudenteachofaSciencestream.HeisunawareoftheexactlocationoftheclassesoftheSciencestreams.Hejustorderstheheadmaster“Bringme,sciencestudent”. Itisnowtheheadmasterwhogoestotheactualclassandcallsastudenttomeetthemanager.Pleasenotethemanagerisopaquetoallthedetailsofhowasciencestudentiscalled. Thisinsomewaysistheuse-caseoftheobjectfactorypattern.Thestudentistheobjectandtheheadmasteristheobjectfactory.Theuser(manager)justtellstheobjectfactory(headmaster)whichkindofobject(student)itneeds,andtheobjectfactory(headmaster)returnsthesamekindofobject(student). Letusnowlookathowwillitlooklikeincodingterms. funcmain(){ student,err:=factory.GetStudent("Science") student.Talk() } Thefactoryistheheadmaster.ThemanagerasksthemanagertogetastudentandjustgivestheinformationthatthestreamisScience.Factory(headmaster)hidingalltheimplementationdetailsfromthemanager,instantiatestheobjectofagiventype(callsthestudentofSciencestream)andreturns.   Golangdoesnothavetheconceptofclassesandobject,butithasstruct{}andinterfaceswhichmorethanmakeupforit. Letusnowlookstepbystep,howtousethisexampleandimplementtheobjectFactoryDesignPatterninGolang. Thisistheparententity(theparentobjectwhichwillbeinstantiatedthroughout).Thisentitywillhavesomebehaviorsrelatingtoit.ThiscanbeachievedinGolangusinginterfaces.Createaninterfacestudentanddefinesomefunctions(behaviors)toit. typeStudentinterface{ Call() } CreateaScienceStudent,whichisanentitythatimplementsthetypeStudent.WewilljustmakeastructandimplementallthefunctionsoftheStudentinterface. packagefactory typeScienceStudentstruct{} func(s*ScienceStudent)Call(){ fmt.Println("Thisisasciencestudent") } OnsimilargroundsmakeArtStudentandCommerceStudent. packagefactory typeArtStudentstruct{} func(s*ArtStudent)Call(){ fmt.Println("Thisisanartsstudent") } typeCommerceStudentstruct{} func(s*CommerceStudent)Call(){ fmt.Println("Thisisacommercestudent") } Nowwehavedefinedthemainentity(student)andit’sdifferentimplementations.Itistimetodefineafactorythattakesintherequirementfromtheuserandreturnstherightimplementationoftheentity. funcGetStudent(subjectstring)Student{ switchsubject{ case"Science": return&ScienceStudent{} case"Commerce": return&CommerceStudent{} case"Arts": return&ArtStudent{} default: fmt.Println("InvalidSubjectgiven") returnnil } } Letusmakeaclienttodrivethecode. packagemain funcmain(){ student:=factory.GetStudent("Science") student.Call() } Andwewiththesesteps.theclientisnotconcernedwiththeimplementationoftheinternalfunctioningoffetchinganinstanceofacertaintype.Hejustcallsamethodtellingthetypeofentityheneeds.Thisisthebeautyoftheobjectfactorypattern. Wewillcontinueexploringmorepatternsinthelaterpostsofthisseries.Inthemeanwhile,refractoryourprojectsandlookwhereyoucanapplythispattern. Categories: DesignPatternsTech 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…



請為這篇文章評分?