Object Factory Design Pattern in Golang - Smartscribs
文章推薦指數: 80 %
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…
延伸文章資訊
- 1Design Patterns in Kubernetes Codebase - DEV Community
Tagged with go, programming, design, opensource. ... returns a new controller builder that will b...
- 2Go All Design Patterns Code with Workflow - DEV Community
Behavioral Patterns Design Pattern Command Design Pattern Command import. ... Println("Booker") }...
- 3All Design Patterns in Go (Golang)
A curated list of design patterns implemented in Go. ... in learning Golang, then for that we hav...
- 4[Golang] Design Pattern | PJCHENder 未整理筆記
[Golang] Design Pattern. golang. Functional Options. 資料來源:GO 程式設計模式:FUNCTIONAL OPTIONS @ 陳皓. 在Go...
- 5Factory Method - Refactoring.Guru
Factory Method is a creational design pattern that provides an interface for creating objects in ...