[设计模式 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)
}
相关推荐
ShareBeHappy_Qin11 小时前
Spring 中使用的设计模式
java·spring·设计模式
Achou.Wang11 小时前
源码分析 golang bigcache 高性能无 GC 开销的缓存设计实现
开发语言·缓存·golang
Yeats_Liao13 小时前
Go语言技术与应用(二):分布式架构设计解析
开发语言·分布式·golang
蓝婴天使13 小时前
基于 React + Go + PostgreSQL + Redis 的管理系统开发框架
react.js·postgresql·golang
脚踏实地的大梦想家13 小时前
【Go】P6 Golang 基础:流程控制
开发语言·golang
QX_hao13 小时前
【Go】--数组和切片
后端·golang·restful
-睡到自然醒~13 小时前
提升应用性能:Go中的同步与异步处理
开发语言·后端·golang
只吃不吃香菜14 小时前
Go WebSocket 协程泄漏问题分析与解决方案
开发语言·websocket·golang
ChineHe14 小时前
Golang并发编程篇001_并发编程相关概念解释
开发语言·后端·golang
赴前尘16 小时前
Go 通道非阻塞发送:优雅地处理“通道已满”的场景
开发语言·后端·golang