抽象工厂

设计模式 / 创建型模式
image

import (
    "fmt"
)

//ProductA is abstract product A
type ProductA interface {
    TestA()
}

//ProductB is abstract product B
type ProductB interface {
    TestB()
}

//Factory is abstract factory
type Factory interface {
    CreateA() ProductA
    CreateB() ProductB
}

//ProductA1 is concrete product A1
type ProductA1 struct{}

//TestA is implementation of the ProductA interface method
func (p ProductA1) TestA() {
    fmt.Println("test A1")
}

//ProductB1 is concrete product B1
type ProductB1 struct{}

//TestB is implementation of the ProductB interface method
func (p ProductB1) TestB() {
    fmt.Println("test B1")
}

//ProductA2 is concrete product A2
type ProductA2 struct{}

//TestA is implementation of the ProductA interface method
func (p ProductA2) TestA() {
    fmt.Println("test A2")
}

//ProductB2 is concrete product B2
type ProductB2 struct{}

//TestB is implementation of the ProductB interface method
func (p ProductB2) TestB() {
    fmt.Println("test B2")
}

//Factory1 is concrete factory 1
type Factory1 struct{}

//CreateA is implementation of the Factory interface method
func (f Factory1) CreateA() ProductA {
    return ProductA1{}
}

//CreateB is implementation of the Factory interface method
func (f Factory1) CreateB() ProductB {
    return ProductB1{}
}

//Factory2 is concrete factory 2
type Factory2 struct{}

//CreateA is implementation of the Factory interface method
func (f Factory2) CreateA() ProductA {
    return ProductA2{}
}

//CreateB is implementation of the Factory interface method
func (f Factory2) CreateB() ProductB {
    return ProductB2{}
}

//client code:

//TestFactory creates and tests factories
func TestFactory(factory Factory) {
    productA := factory.CreateA()
    productB := factory.CreateB()
    productA.TestA()
    productB.TestB()
}

TestFactory(Factory1{})
//printed: test A1
//         test B1
TestFactory(Factory2{})
//printed: test A2
//         test B2


Provides an interface for creating families of objects whose interfaces are known but concrete classes are not.
Read more

问题。程序用浅色和深色两种风格绘制窗口。每种风格都需要自己的按钮和菜单。如果代码直接创建它们,就可能误把浅色按钮和深色菜单混在一起。增加第三种风格时,还得找出所有创建按钮或菜单的地方。

思路。抽象工厂是一个接口,为每一种产品提供一个创建方法。每个具体工厂为一个产品族实现这个接口:一个工厂创建浅色按钮和浅色菜单,另一个创建深色的。客户端拿到一个工厂,所有产品都通过它来创建。客户端从不指明具体产品,因此得到的产品总是属于同一个产品族。要更换整个产品族,只需给客户端换一个工厂。

如何阅读示例。示例中有 A、B 两种产品。一个具体工厂生产一个产品族:每种产品各一个,标有相同的编号。客户端拿到一个工厂,向它各要一种产品,并使用这两个产品。客户端不知道自己拿到的是哪个产品族,但输出会显示出来。有些语言根本不声明接口,但角色不变。

何时使用。当产品必须配合使用、而且有多个产品族时,例如界面风格或操作系统,使用抽象工厂模式。只有一个产品族时不要使用它。产品之间互不依赖时也不需要它:构造函数或工厂方法就够了。

常见错误。在产品种类还经常变化时就选用这个模式。每增加一种产品,都要在抽象工厂和每个具体工厂中增加一个方法。