Factory Design Pattern in Go (Golang)
文章推薦指數: 80 %
Factory design pattern is a creational design pattern and it is also one of the most commonly used pattern. This pattern provides a way to ... Note:InterestedinunderstandinghowallotherdesignpatternscanbeimplementedinGO.Pleaseseethisfullreference–AllDesignPatternsinGo(Golang) TableofContents Introduction: UMLDiagram:Mapping:Example: FullWorkingCode: Introduction: Factorydesignpatternisacreationaldesignpatternanditisalsooneofthemostcommonlyusedpattern.Thispatternprovidesawaytohidethecreationlogicoftheinstancesbeingcreated.Theclientonlyinteractswithafactorystructandtellsthekindofinstancesthatneedstobecreated.Thefactoryclassinteractswiththecorrespondingconcretestructsandreturnsthecorrectinstanceback.Inbelowexample WehaveiGuninterfacewhichdefinesallmethodsagunshouldhaveThereisgunstructthatimplementstheiGuninterface.Twoconcretegunsak47andmaverick.BothembedgunstructandhencealsoindirectlyimplementallmethodsofiGunandhenceareofiGuntypeWehaveagunFactorystructwhichcreatesthegunoftypeak47ormaverick.Themain.goactsasaclientandinsteadofdirectlyinteractingwithak47ormaverick,itreliesongunFactorytocreateinstancesofak47andmaverick UMLDiagram: BelowisthecorrespondingmappingUMLdiagramwiththeexamplegivenabove Mapping: ThebelowtablerepresentsthemappingfromtheUMLdiagramactorstoactualimplementationactorsin“Example”below ProductFactorygunFactory.goiProductiGun.goProductgun.goConcreteiProduct1ak47goConcreteiProduct1maverick.goClientmain.go Example: iGun.go packagemain typeiGuninterface{ setName(namestring) setPower(powerint) getName()string getPower()int } gun.go packagemain typegunstruct{ namestring powerint } func(g*gun)setName(namestring){ g.name=name } func(g*gun)getName()string{ returng.name } func(g*gun)setPower(powerint){ g.power=power } func(g*gun)getPower()int{ returng.power } ak47.go packagemain typeak47struct{ gun } funcnewAk47()iGun{ return&ak47{ gun:gun{ name:"AK47gun", power:4, }, } } maverick.go packagemain typemaverickstruct{ gun } funcnewMaverick()iGun{ return&maverick{ gun:gun{ name:"Maverickgun", power:5, }, } } gunFactory.go packagemain import"fmt" funcgetGun(gunTypestring)(iGun,error){ ifgunType=="ak47"{ returnnewAk47(),nil } ifgunType=="maverick"{ returnnewMaverick(),nil } returnnil,fmt.Errorf("Wrongguntypepassed") } main.go packagemain import"fmt" funcmain(){ ak47,_:=getGun("ak47") maverick,_:=getGun("maverick") printDetails(ak47) printDetails(maverick) } funcprintDetails(giGun){ fmt.Printf("Gun:%s",g.getName()) fmt.Println() fmt.Printf("Power:%d",g.getPower()) fmt.Println() } Output: Gun:AK47gun Power:4 Gun:Maverickgun Power:5 FullWorkingCode: packagemain import"fmt" typeiGuninterface{ setName(namestring) setPower(powerint) getName()string getPower()int } typegunstruct{ namestring powerint } func(g*gun)setName(namestring){ g.name=name } func(g*gun)getName()string{ returng.name } func(g*gun)setPower(powerint){ g.power=power } func(g*gun)getPower()int{ returng.power } typeak47struct{ gun } funcnewAk47()iGun{ return&ak47{ gun:gun{ name:"AK47gun", power:4, }, } } typemaverickstruct{ gun } funcnewMaverick()iGun{ return&maverick{ gun:gun{ name:"Maverickgun", power:5, }, } } funcgetGun(gunTypestring)(iGun,error){ ifgunType=="ak47"{ returnnewAk47(),nil } ifgunType=="maverick"{ returnnewMaverick(),nil } returnnil,fmt.Errorf("Wrongguntypepassed") } funcmain(){ ak47,_:=getGun("ak47") maverick,_:=getGun("maverick") printDetails(ak47) printDetails(maverick) } funcprintDetails(giGun){ fmt.Printf("Gun:%s",g.getName()) fmt.Println() fmt.Printf("Power:%d",g.getPower()) fmt.Println() } Output: Gun:AK47gun Power:4 Gun:Maverickgun Power:5 factorygopattern Follow@golangbyexample Searchfor: PopularArticles GolangComprehensiveTutorialSeries AllDesignPatternsinGo(Golang) Sliceingolang VariablesinGo(Golang)–CompleteGuide OOP:InheritanceinGOLANGcompleteguide UsingContextPackageinGO(Golang)–CompleteGuide AlldatatypesinGolangwithexamples UnderstandingtimeanddateinGo(Golang)–CompleteGuide
延伸文章資訊
- 1Design Patterns: Factory Method in Go - Refactoring.Guru
Factory method is a creational design pattern which solves the problem of creating product object...
- 2Factory Design Pattern in Go - DEV Community
I've been studying a little bit on design patterns in Go since it's the ... So without further ad...
- 3Factory Design Pattern in GoLang - Yashod Perera
Factory design pattern is a creational design pattern to predefined blueprint of a solution for a...
- 4Golang Factory Method - Stack Overflow
Nevertheless, if you really need to implement this design pattern in Go, read further. The factor...
- 5Factory Design Pattern in Go (Golang)
Factory design pattern is a creational design pattern and it is also one of the most commonly use...