Go 实现常用设计模式(六)工厂模式
工厂模式 (factory)
意图:
定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行
主要解决接口选择问题
关键代码:
返回的实例都实现同一接口
应用实例:
- 您需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个汽车里面的具体实现。
- Hibernate 换数据库只需换方言和驱动就可以。
Go实现工厂模式
1. 简单工厂模式
package simple
import "fmt"
// 简单工厂模式
type Girl interface {
weight()
}
// 胖女孩
type FatGirl struct {
}
func (FatGirl) weight() {
fmt.Println("80kg")
}
// 瘦女孩
type ThinGirl struct {
}
func (ThinGirl) weight() {
fmt.Println("50kg")
}
type GirlFactory struct {
}
func (*GirlFactory) CreateGirl(like string) Girl {
if like == "fat" {
return &FatGirl{}
} else if like == "thin" {
return &ThinGirl{}
}
return nil
}
2. 抽象工厂模式
package abstract
import (
"fmt"
)
// 抽象工厂模式
type Girl interface {
weight()
}
// 中国胖女孩
type FatGirl struct {
}
func (FatGirl) weight() {
fmt.Println("chinese girl weight: 80kg")
}
// 瘦女孩
type ThinGirl struct {
}
func (ThinGirl) weight() {
fmt.Println("chinese girl weight: 50kg")
}
type Factory interface {
CreateGirl(like string) Girl
}
// 中国工厂
type ChineseGirlFactory struct {
}
func (ChineseGirlFactory) CreateGirl(like string) Girl {
if like == "fat" {
return &FatGirl{}
} else if like == "thin" {
return &ThinGirl{}
}
return nil
}
// 美国工厂
type AmericanGirlFactory struct {
}
func (AmericanGirlFactory) CreateGirl(like string) Girl {
if like == "fat" {
return &AmericanFatGirl{}
} else if like == "thin" {
return &AmericanThainGirl{}
}
return nil
}
// 美国胖女孩
type AmericanFatGirl struct {
}
func (AmericanFatGirl) weight() {
fmt.Println("American weight: 80kg")
}
// 美国瘦女孩
type AmericanThainGirl struct {
}
func (AmericanThainGirl) weight() {
fmt.Println("American weight: 50kg")
}
// 工厂提供者
type GirlFactoryStore struct {
factory Factory
}
func (store *GirlFactoryStore) createGirl(like string) Girl {
return store.factory.CreateGirl(like)
}
具体代码
更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了 Go 常用的设计模式、Go 面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个 Star
,你的支持,是我最大的动力!
本作品采用《CC 协议》,转载必须注明作者和本文链接