[设计模式 Go实现] 创建型~ 原型模式

原型模式使对象能复制自身,并且暴露到接口中,使客户端面向接口编程时,不知道接口实际对象的情况下生成新的对象。

原型模式配合原型管理器使用,使得客户端在不知道具体类的情况下,通过接口管理器得到新的实例,并且包含部分预设定配置。

代码实现

go 复制代码
package prototype

//Cloneable 是原型对象需要实现的接口
type Cloneable interface {
	Clone() Cloneable
}

type PrototypeManager struct {
	prototypes map[string]Cloneable
}

func NewPrototypeManager() *PrototypeManager {
	return &PrototypeManager{
		prototypes: make(map[string]Cloneable),
	}
}

func (p *PrototypeManager) Get(name string) Cloneable {
	return p.prototypes[name].Clone()
}

func (p *PrototypeManager) Set(name string, prototype Cloneable) {
	p.prototypes[name] = prototype
}

单元测试

go 复制代码
package prototype

import "testing"

var manager *PrototypeManager

type Type1 struct {
	name string
}

func (t *Type1) Clone() Cloneable {
	tc := *t
	return &tc
}

type Type2 struct {
	name string
}

func (t *Type2) Clone() Cloneable {
	tc := *t
	return &tc
}

func TestClone(t *testing.T) {
	t1 := manager.Get("t1")

	t2 := t1.Clone()

	if t1 == t2 {
		t.Fatal("error! get clone not working")
	}
}

func TestCloneFromManager(t *testing.T) {
	c := manager.Get("t1").Clone()

	t1 := c.(*Type1)
	if t1.name != "type1" {
		t.Fatal("error")
	}

}

func init() {
	manager = NewPrototypeManager()

	t1 := &Type1{
		name: "type1",
	}
	manager.Set("t1", t1)
}
相关推荐
ximu_polaris9 小时前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式
sweetheart7-714 小时前
go/golang 入门学习笔记(Java/Python/C++转Go快速上手)
笔记·学习·golang·go语言
诙_16 小时前
深入理解C++设计模式
c++·设计模式
AI大法师18 小时前
从门头到社媒预热图,快闪项目如何统一视觉输出
大数据·人工智能·设计模式
Vect__19 小时前
C++无痛转go第一天,从hello world到切片
开发语言·c++·golang
Pkmer20 小时前
类的封装性: 让门面设计模式来打开这扇门
后端·设计模式
Pkmer20 小时前
古法编程: 我要的是状态模式,策略模式不要误我大计
后端·设计模式
雪度娃娃21 小时前
创建型设计模式——建造者模式
c++·microsoft·设计模式·建造者模式
老衲提灯找美女21 小时前
多线程(2)-设计模式:单列模式
设计模式
研究点啥好呢2 天前
字节跳动Go后端开发工程师面试题精选:10道高频考题+答案解析
面试·golang·php·求职招聘