《大话设计模式》抽象工厂模式

抽象工厂模式(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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值