[设计模式 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
}

单元测试

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)
}

相关推荐

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

    2024-01-05 10:42:05       38 阅读
  2. GO设计模式——6、原型模式创建

    2024-01-05 10:42:05       38 阅读
  3. [设计模式 Go实现] 创建~单例模式

    2024-01-05 10:42:05       36 阅读
  4. [设计模式 Go实现] 创建~建造者模式

    2024-01-05 10:42:05       39 阅读
  5. 设计模式创建模式原型模式

    2024-01-05 10:42:05       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-05 10:42:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-05 10:42:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-05 10:42:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-05 10:42:05       18 阅读

热门阅读

  1. Ansibe自动化基础

    2024-01-05 10:42:05       26 阅读
  2. prototype 和 __proto__

    2024-01-05 10:42:05       37 阅读
  3. 游戏策划:游戏开发中的关键环节

    2024-01-05 10:42:05       38 阅读
  4. 远程控制软件排名(2024)

    2024-01-05 10:42:05       38 阅读
  5. Android 13.0 recovery竖屏界面旋转为横屏

    2024-01-05 10:42:05       39 阅读
  6. 智能旅游代步车控制系统设计

    2024-01-05 10:42:05       36 阅读