分享
  1. 首页
  2. 文章

型模式

nodeadbird · · 628 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

6.1. 模式动机

原型模式用于创建重复的对象。当一个类在创建时开销比较大时(比如大量数据准备,数据库连接),我们可以缓存该对象,当下一次调用时,返回该对象的克隆。

6.2. 模式定义

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。通过实现克隆clone()操作,快速的生成和原型对象一样的实例。

6.3. 代码分析

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


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:nodeadbird

查看原文:型模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
628 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏