🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 示例 ### 概念示例 <details> <summary>main.go</summary> ``` package main type Product interface { SetName(name string) GetName() string } type Product1 struct { name string } func (p *Product1) SetName(name string) { p.name=name } func (p Product1) GetName() string { return "Product1's name"+p.name } type Product2 struct { name string } func (p *Product2) SetName(name string) { p.name=name } func (p Product2) GetName() string { return "Product2's name"+p.name } type productType int const ( p1 productType=iota p2 ) type productFactory struct { } func (pf productFactory) Create(productType productType) Product{ switch productType { case p1: return &Product1{} case p2: return &Product2{} default: return nil } } ``` </details> <br /> 优点:实现了解耦 缺点:违背 "开闭原则" 适合:创建的对象比较少 ### 武器工厂 <details> <summary>main.go</summary> ``` package main import "fmt" // 产品接口 type iGun interface { setName(name string) setPower(power int) getName() string getPower() int } type gun struct { name string power int } func (g *gun) setName(name string) { g.name = name } func (g *gun) getName() string { return g.name } func (g *gun) setPower(power int) { g.power = power } func (g *gun) getPower() int { return g.power } // 具体产品 type ak47 struct { gun } func newAk47() iGun { return &ak47{ gun: gun{ name: "AK47 gun", power: 4, }, } } type musket struct { gun } func newMusket() iGun { return &musket{ gun: gun{ name: "Musket gun", power: 1, }, } } // 工厂 func getGun(gunType string) (iGun, error) { if gunType == "ak47" { return newAk47(), nil } if gunType == "musket" { return newMusket(), nil } return nil, fmt.Errorf("Wrong gun type passed") } func main() { ak47, _ := getGun("ak47") musket, _ := getGun("musket") printDetails(ak47) printDetails(musket) } func printDetails(g iGun) { fmt.Printf("Gun: %s", g.getName()) fmt.Println() fmt.Printf("Power: %d", g.getPower()) fmt.Println() } ``` </details> <br /> 输出 ``` Gun: AK47 gun Power: 4 Gun: Musket gun Power: 1 ```