[04]Go设计模式:抽象工厂模式(Abstract Factory Pattern)

抽象工厂模式

一、简介

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
使用抽象工厂模式一般要满足以下条件。

  • 系统中有多个产品族,每个具体工厂创建同一族但属于不同等级结构的产品。
  • 系统一次只可能消费其中某一族产品,即同族的产品一起使用。

抽象工厂模式除了具有工厂方法模式的优点外,其他主要优点如下。

  • 可以在类的内部对产品族中相关联的多等级产品共同管理,而不必专门引入多个新的类来进行管理。
  • 当增加一个新的产品族时不需要修改原代码,满足开闭原则。

其缺点是:当产品族中需要增加一个新的产品时,所有的工厂类都需要进行修改。

二、代码

package main

import "fmt"


type Phone interface {
	Show()
}

type PhoneCreator interface {
	Create() Phone
}

type HuaweiPhone struct {
	Brand string
}

func (h *HuaweiPhone) Show() {
	fmt.Printf("I am %s phone\n", h.Brand)
}

type HuaweiPhoneCreator struct {
}

func (x *HuaweiPhoneCreator) Create() Phone {
	s := &HuaweiPhone{
		Brand:"HuaWei",
	}
	return s
}

type XiaoMiPhone struct {
	Brand string
}

func (x *XiaoMiPhone) Show () {
	fmt.Printf("I am %s phone\n", x.Brand)
}

type XiaoMiPhoneCreator struct {
}

func (c *XiaoMiPhoneCreator) Create() Phone {
	s := &XiaoMiPhone{
		Brand:"XiaoMi",
	}
	return s
}


func CreatePhone(brand string){
	var c PhoneCreator
	if brand == "HuaWei"{
		c = new(HuaweiPhoneCreator)
		p := c.Create()
		p.Show()
	}else{
		c = new(XiaoMiPhoneCreator)
		f := c.Create()
		f.Show()
	}
}


func main() {
	CreatePhone("HuaWei")
	CreatePhone("XiaoMi")
}

三、 参考资料

1、 http://c.biancheng.net/view/1351.html

2、 https://www.runoob.com/design-pattern/abstract-factory-pattern.html

posted @ 2019-12-15 16:48  0pandas0  阅读(249)  评论(0编辑  收藏  举报