二、工厂模式

43 阅读1分钟

简单工厂

在实现工厂模式的时候,我们通常会使用一个接口来模拟工厂,然后根据实际创建具体的工厂类。每一种工厂类都对应着一种具体的产品对象,并实现工厂接口中的方法。

下面这个例子中,动物可能会有许多种,我们需要传入动物的名字来获取对应的动物类,那么我们就可以使用简单工厂模式:

// Animals 工厂接口
type Animals interface {
	Cry()
}

// Dog 具体工厂类
type Dog struct {
}

func (d *Dog) Cry() {
	fmt.Println("汪汪")
}

// Cat 具体工厂类
type Cat struct {
}

func (d *Cat) Cry() {
	fmt.Println("喵喵")
}

func NewAnimals(name string) Animals {
	switch name {
	case "Dog":
		return new(Dog)
	case "Cat":
		return new(Cat)
	default:
		return new(Dog)
	}
}

func main() {
	an := NewAnimals("Dog")
	an.Cry()
}

我们只需要告诉工厂我们需要哪一个动物实例,那么工厂就会返回对应的动物实例。

工厂方法

抽象工厂