工厂模式
此开源图书由ithaiq原创,创作不易转载请注明出处
简单工厂模式
type IHuman interface {
Watch() string
}
type Man struct{}
func (t *Man) Watch() string {
return "man"
}
type Woman struct{}
func (t *Woman) Watch() string {
return "woman"
}
const (
ManN = iota
WomanN
)
func CreateHuman(id int) IHuman {
switch id {
case ManN:
return new(Man)
case WomanN:
return new(Woman)
}
return nil
}
抽象工厂模式
设计模式原则-对修改关闭,多扩展开放
type IHuman interface {
Watch() string
}
type Man struct{}
func (t *Man) Watch() string {
return "man"
}
type Woman struct{}
func (t *Woman) Watch() string {
return "woman"
}
type AbstractFactory interface {
CreateHuman() IHuman
}
type ManFactory struct{}
func (f *ManFactory) CreateHuman() IHuman {
return new(Man)
}
type WomanFactory struct{}
func (f *WomanFactory) CreateHuman() IHuman {
return new(Woman)
}
最后更新于
这有帮助吗?