NOTE
6.13 抽象工厂
1. 是什么 有多种产品,每种产品对应一个工厂,同时这个产品需要多个小产品组合而成 抽象工厂模式用于生成产品族的工厂,所生成的产品是有关联的 2. Golang 2.1. 产品 2.2. 工厂 2.3. client
这是历史学习笔记,可能存在过时或不完整的理解。
1. 是什么
有多种产品,每种产品对应一个工厂,同时这个产品需要多个小产品组合而成 抽象工厂模式用于生成产品族的工厂,所生成的产品是有关联的
2. Golang
2.1. 产品
/*车有引擎*/
type Engine interface {
Create()
}
type QQEngine struct {
}
func (Q QQEngine) Create() {
fmt.Println("创建QQ引擎")
}
type AodiEngine struct {
}
func (AodiEngine) Create() {
fmt.Println("创建Aodi引擎")
}
/*车有轮子*/
type Wheel interface {
Create()
}
type QQWheel struct {
}
func (Q QQWheel) Create() {
fmt.Println("创建QQ轮子")
}
type AodiWheel struct {
}
func (a AodiWheel) Create() {
fmt.Println("创建Aodi轮子")
}
2.2. 工厂
/*创建车子的工厂*/
type CarFactory interface {
CreateEngine() Engine
CreateWheel() Wheel
}
type QQCarFactory struct {
}
func (Q QQCarFactory) CreateEngine() Engine {
return &QQEngine{}
}
func (Q QQCarFactory) CreateWheel() Wheel {
return &QQWheel{}
}
type AodiCarFactory struct {
}
func (a AodiCarFactory) CreateEngine() Engine {
return &AodiEngine{}
}
func (a AodiCarFactory) CreateWheel() Wheel {
return &AodiWheel{}
}
2.3. client
func main() {
BuildCar(&抽象工厂.QQCarFactory{})
BuildCar(&抽象工厂.AodiCarFactory{})
}
func BuildCar(factory 抽象工厂.CarFactory) {
factory.CreateEngine().Create()
factory.CreateWheel().Create()
}
讨论
使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看