抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
优点:
-
易于更换产品系列
由于具体工厂类,在一个应用中只需要在初始化的时候出现一次,这就使得改变一个应用的具体工厂变得非常容易,它只需要改变具体工厂即可使用不同的产品配置。我们的设计不能去防止需求的更改,那么我们的理想便是让改动变得最小,现在如果你要更改数据库访问,我们只需要更改具体工厂就可以做到。
-
降低耦合
让具体的创建实例过程与客户端分离,客户端是通过它们的抽象接口操纵实例,产品的具体类名也被具体工厂的实现分离,不会出现在客户代码中
缺点:
-
扩展新产品时需要修改工厂接口以及所有具体工厂类
也就违背了开放-封闭原则
// 产品1"父类"
type Cat struct {}
// 产品1"子类"需实现接口
type CatInterface interface {
CatShout()
}
// 产品1的具体"子类1"
type SmallCat struct {
Cat
}
func (c *SmallCat) CatShout() {
fmt.Println("I'm small cat.")
}
// 产品1的具体"子类2"
type Tiger struct {
Cat
}
func (t *Tiger) CatShout() {
fmt.Println("I'm tiger.")
}
// 产品2的"父类"
type Dog struct {}
// 产品2系列的"子类"需实现的接口
type DogInterface interface {
DogShout()
}
// 产品2的具体"子类1"
type SmallDog struct {
Dog
}
func (d *SmallDog) DogShout() {
fmt.Println("I'm small dog.")
}
// 产品2的具体"子类2"
type Wolf struct {
Dog
}
func (w *Wolf) DogShout() {
fmt.Println("I'm wolf.")
}
// 抽象工厂"父类"
type AnimalsFactory struct {}
// 抽象工厂"子类"待实现的接口
type AnimalFactoryInterface interface {
CreateCat() CatInterface
CreateDog() DogInterface
}
// 抽象工厂"子类1"
type BigAnimalFactory struct {
AnimalsFactory
}
func (s *BigAnimalFactory) CreateCat() CatInterface {
return &Tiger{}
}
func (s *BigAnimalFactory) CreateDog() DogInterface {
return &Wolf{}
}
// 抽象工厂"子类2"
type SmallAnimalFactory struct {
AnimalsFactory
}
func (s *SmallAnimalFactory) CreateCat() CatInterface {
return &SmallCat{}
}
func (s *SmallAnimalFactory) CreateDog() DogInterface {
return &SmallDog{}
}
func main() {
var (
factory AnimalFactoryInterface
cat CatInterface
dog DogInterface
)
// 抽象工厂1创建系列1
factory = &SmallAnimalFactory{}
cat = factory.CreateCat()
cat.CatShout()
dog = factory.CreateDog()
dog.DogShout()
// 抽象工厂2创建系列2
factory = &BigAnimalFactory{}
cat = factory.CreateCat()
cat.CatShout()
dog = factory.CreateDog()
dog.DogShout()
}
// 输出
// I'm small cat.
// I'm small dog.
// I'm tiger.
// I'm wolf.