Go实现抽象工厂模式

71 阅读1分钟

相较于工厂模式,在我们每次增加工厂的时候。都需要这样的代码

 // strawberry
 type Strawberry struct{}
 
 func (a *Strawberry) Show() {
     fmt.Println("我是Strawberry")
 }
 type StrawberryFactory struct{}
 
 func (af *StrawberryFactory) CreateFruit() Fruit {
     return new(Strawberry)
 }

每次多创建一个StrawberryFactory。

也就是说产品增加,产品的工厂也需要增加,1比1的关系。抽象工厂模式解决这样的问题

抽象工厂设计模式也是一种创建型设计模式,它提供了一种方法来创建相关或依赖对象的家族,而无需指定他们具体的类。

优点:

  1.  拥有工厂方法模式的优点
  2. 当一个产品族中的多个对象被设计成一起工作时,它能够保证客户端始终只使用同一个产品族中的对象。
    3   增加新的产品族很方便,无须修改已有系统,符合“开闭原则”。

缺点:

  1. 增加新的产品等级结构麻烦,需要对原有系统进行较大的修改,甚至需要修改抽象层代码,这显然会带来较大的不便,违背了 “开闭原则”

下面就是中午做饭的例子CreateFoodCreateVegetable都实现了Lunch这个接口:

package abstractfactory

import "fmt"

type Lunch interface {
	Cook()
}
type rise struct{}

func (r *rise) Cook() {
	fmt.Println("煮米饭")
}

type Tomato struct{}

func (t *Tomato) Cook() {
	fmt.Println("炒土豆丝")
}

type LunchFactory interface {
	CreateFood() Lunch
	CreateVegetable() Lunch
}
type SimpleLunchFactory struct{}

func (s *SimpleLunchFactory) CreateFood() Lunch {
	return &rise{}
}
func (s *SimpleLunchFactory) CreateVegetable() Lunch {
	return &Tomato{}
}

func NewSimpleLuchFactory() LunchFactory {
	return &SimpleLunchFactory{}
}

最后可根据不同的口味来做不同的菜:

lunch := NewSimpleLuchFactory{}
rice := lunch.CreateFood()
tomato := lunch.CreateVegetable()