golang 工廠方法模式

概念

  1. 工廠方法模式又稱爲工廠模式,也叫虛擬構造器模式或者多態工廠模式,它屬於類創建型模式
  2. 在工廠方法模式中,工廠父類負責定義創建產品對象的公共接口,而工廠子類則負責生成具體的產品對象

結構圖

總結

  1. 保持了簡單工廠模式的優點,克服了簡單工廠模式的缺點
  2. 在添加新產品時,在一定程度上增加了系統的複雜度
  3. 適合調用者不需要知道具體產品類的類名,只需要知道所對應的工廠即可

示例代碼1

package demo1

// 工廠方法模式

type Product interface {
	SetName(name string)
	GetName() string
}

// 產品1
type Product1 struct {
	name string
}

func (p1 *Product1) SetName(name string) {
	p1.name = name
}

func (p1 *Product1) GetName() string {
	return "prod1 name is: " + p1.name
}

// 產品2
type Product2 struct {
	name string
}

func (p2 *Product2) SetName(name string) {
	p2.name = name
}

func (p2 *Product2) GetName() string {
	return "prod2 name is: " + p2.name
}

// 抽象工廠接口
type FactoryProduct interface {
	Create() Product
}

type FactoryProduct1 struct{}

func (fp1 *FactoryProduct1) Create() Product {
	return &Product1{}
}

type FactoryProduct2 struct{}

func (fp2 *FactoryProduct2) Create() Product {
	return &Product2{}
}

package demo1

import (
	"testing"
)

func TestFactoryProduct1(t *testing.T) {
	factory := (&FactoryProduct1{}).Create()
	factory.SetName("zhangsan")
	t.Logf(factory.GetName())
}

func TestFactoryProduct2(t *testing.T) {
	factory := (&FactoryProduct2{}).Create()
	factory.SetName("lisi")
	t.Logf(factory.GetName())
}

示例代碼2

package cache2

// cache 接口定義,作爲父類
type Cache interface {
	SetValue(key string, value string)
	GetValue(key string) string
}

// 實現具體的cache: redis
type RedisCache struct {
	data map[string]string
}

func (r *RedisCache) SetValue(key string, value string) {
	r.data[key] = value
}

func (r *RedisCache) GetValue(key string) string {
	return "redis:" + r.data[key]
}

func NewRedisCache() *RedisCache {
	return &RedisCache{
		data: make(map[string]string),
	}
}

// 實現具體的cache: memory
type MemoryCache struct {
	data map[string]string
}

func (r *MemoryCache) SetValue(key string, value string) {
	r.data[key] = value
}

func (r *MemoryCache) GetValue(key string) string {
	return "memory:" + r.data[key]
}

func NewMemoryCache() *MemoryCache {
	return &MemoryCache{
		data: make(map[string]string),
	}
}

// 實現cache的工廠方法
type CacheFactory interface {
	Create() Cache
}

type RedisCacheFactory struct{}

func (rcf *RedisCacheFactory) Create() Cache {
	return NewRedisCache()
}

type MemoryCacheFactory struct{}

func (mcf *MemoryCacheFactory) Create() Cache {
	return NewMemoryCache()
}

package cache2

import (
	"testing"
)

func TestRedisCacheFactory(t *testing.T) {
	var factory CacheFactory
	factory = &RedisCacheFactory{}
	cache := factory.Create()
	cache.SetValue("k1", "v1")
	t.Logf(cache.GetValue("k1"))
}

func TestMemoryCacheFactory(t *testing.T) {
	var factory CacheFactory
	factory = &MemoryCacheFactory{}
	cache := factory.Create()
	cache.SetValue("k2", "v2")
	t.Logf(cache.GetValue("k2"))
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章