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

单元测试

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)
}
相关文章
|
5天前
|
设计模式
**工厂模式与抽象工厂模式**都是创建型设计模式,用于封装对象创建,减少耦合
【6月更文挑战第23天】**工厂模式与抽象工厂模式**都是创建型设计模式,用于封装对象创建,减少耦合。工厂模式专注于单个对象,通过具体工厂创建具体产品,适用于简单对象创建;抽象工厂则关注一系列相关产品,提供创建一族对象的接口,适用于处理多个不兼容产品族。选择模式基于问题域的复杂性,单个产品需求时用工厂模式,多产品族时用抽象工厂模式。
14 5
|
1月前
|
设计模式 搜索推荐 数据库连接
第二篇 创建型设计模式 - 灵活、解耦的创建机制
第二篇 创建型设计模式 - 灵活、解耦的创建机制
|
8天前
|
设计模式 Oracle Java
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。
【6月更文挑战第20天】工厂模式简化对象创建,根据参数或条件生成MySQL或Oracle数据库连接。`DatabaseConnectionFactory`作为工厂,动态返回具体连接类型。装饰器模式则用于运行时动态增加对象功能,如`LoggingDecorator`为`Runnable`对象添加日志记录,保持代码整洁。在`Main`类中展示了如何使用这两种模式。
23 6
|
2天前
|
设计模式 Java
Java设计模式之原型模式详解
Java设计模式之原型模式详解
|
2天前
|
设计模式
原型模式-大话设计模式
原型模式-大话设计模式
6 0
|
7天前
|
设计模式
创建型设计模式之建造者模式
创建型设计模式之建造者模式
|
7天前
|
设计模式 Java Spring
设计模式——原型模式
设计模式——原型模式
|
20天前
|
设计模式 存储 架构师
设计模式-值类型与引用类型、深拷贝与浅拷贝、原型模式详解
 如果拷贝的时候共享被引用的对象就是浅拷贝,如果被引用的对象也拷贝一份出来就是深拷贝。(深拷贝就是说重新new一个对象,然后把之前的那个对象的属性值在重新赋值给这个用户)
147 0
|
1月前
|
设计模式 Go
[设计模式 Go实现] 结构型~享元模式
[设计模式 Go实现] 结构型~享元模式
|
1月前
|
设计模式 Go API
[设计模式 Go实现] 结构型~外观模式
[设计模式 Go实现] 结构型~外观模式