chiachan
chiachan
Published on 2020-08-21 / 612 Visits
0

Factory Method模式(工厂方法模式)

什么是工厂方法模式?

  • 工厂方法模式即将实例的生成交给子类,用Template模式来构建生成实例的工厂
  • 不必New关键字来生成实例,而是调用生成实例的专用方法来生成实例,这样就可以防止父类与其他具体类耦合

示范代码(factory.go)

创建一个工厂,用于生产通行证

package Factory

import "fmt"

// 生产的产品
type ProductInterface interface {
	use()
}

// 工厂
type FactoryInterface interface {
	Create(owner string) interface{}
	CreateProduct(owner string) interface{}
	RegisterProduct(product interface{})
}

// 通行证工厂
type IDCardFactory struct {
	Owners []*IDCard
	FactoryInterface
}

func (f *IDCardFactory) Create(owner string) *IDCard {
	p := f.CreateProduct(owner)
	f.RegisterProduct(p)
	return p
}

func (f *IDCardFactory) CreateProduct(owner string) *IDCard {
	fmt.Println("创建", owner, "的ID卡")
	return &IDCard{Owner: owner}
}

func (f *IDCardFactory) RegisterProduct(product *IDCard) {
	f.Owners = append(f.Owners, product)
}

func (f *IDCardFactory) GetOwners() []*IDCard {
	return f.Owners
}

// 具体的产品 通行证
type IDCard struct {
	Owner string
	ProductInterface
}

func (c *IDCard) NewIDCard(owner string) *IDCard {
	return &IDCard{
		Owner: owner,
	}
}

func (c *IDCard) use() {
	fmt.Println("使用", c.Owner, "的ID卡")
}

测试用例(factory_test.go)

package Factory

import (
	"fmt"
	"testing"
)

func TestFactory_Create(t *testing.T) {
	f := &IDCardFactory{}
	p1 := f.Create("小明")
	p2 := f.Create("小红")
	p3 := f.Create("小刚")
	p1.use()
	p2.use()
	p3.use()
	fmt.Println("工厂已有的IDCard:")
	for i, _idCard := range f.GetOwners() {
		fmt.Println(i+1, _idCard.Owner)
	}
}