Go Factory MethodPattern explanation and code examples
Concept example
Due to the lack of OOP features such as classes and inheritance in Go, it is impossible to use Go to implement the classic factory method pattern. However, we can still implement the basic version of the model, namely the simple factory.
In this case, we will use the factory structure to build multiple types of weapons.
First, let's create aiGun
The interface of which will define all the methods required for a gun. Then there is the iGun interface implementedgun
Gun structure type. Two specific guns—ak47
andmusket
Musket - Both are embedded in the gun structure and indirectly realize alliGun
method.
gunFactory
The gun factory structure will play the role of the factory, that is, to build the required type of gun through incoming parameters. It plays the role of the client. It will not be directly related toak47
ormusket
Interact, but rely ongunFactory
To create multiple instances of guns, only character parameters are used to control production.
:Product interface
package main type iGun interface { setName(name string) setPower(power string) getName() string getPower() string }
:Specific products
package main type Gun struct { name string power int } func (g *Gun) setName(name string) { = name } func (g *Gun) setPower(power int) { = power } func (g *Gun) getName() string { return } func (g *Gun) getPower() int { return }
:Specific products
package main type Ak47 struct { Gun } func newAk47() iGun { return &Ak47{ Gun: Gun{ name: "AK47 gun", power: 4, }, } }
:Specific products
package main type musket struct { Gun } func newMusket() iGun { return &musket{ Gun: Gun{ name: "Musket gun", power: 1, }, } }
:factory
package main import "fmt" func getGun(gunType string) (iGun, error) { switch gunType { case "ak47": return newAk47(), nil case "nusket": return newMusket(), nil default: return nil, ("Wrong gun type passed") } }
:Client code
package main import "fmt" func main() { ak47, _ := getGun("ak47") musket, _ := getGun("musket") printDetails(ak47) printDetails(musket) } func printDetails(g iGun) { ("Gun: %s", ()) () ("Power: %d", ()) () }
This is the article about the explanation of factory method model and code examples of Golang design pattern. For more related content of Golang factory method model, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!