[设计模式 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)
}
相关推荐
MarkHD8 分钟前
RPA工程化实践:三种核心设计模式让复杂流程优雅可控
linux·设计模式·rpa
AI大法师39 分钟前
字标Logo设计指南:中文品牌如何用字体做出高级感与辨识度
人工智能·设计模式
Yu_Lijing1 小时前
基于C++的《Head First设计模式》笔记——中介者模式
笔记·设计模式·中介者模式
程序员小寒2 小时前
JavaScript设计模式(四):发布-订阅模式实现与应用
开发语言·前端·javascript·设计模式
ruxingli3 小时前
GoLang channel管道
开发语言·后端·golang
_DCG_3 小时前
go第一个工程安装过程与问题汇总
开发语言·后端·golang
是糖糖啊4 小时前
Agent 不好用?先别怪模型,试试 Harness Engineering
人工智能·设计模式
jiankeljx4 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
WarrenMondeville4 小时前
5.Unity面向对象-依赖倒置原则
unity·设计模式·依赖倒置原则
onlywhz5 小时前
GO 快速升级Go版本
开发语言·redis·golang