前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go设计模式之原型模式

go设计模式之原型模式

原创
作者头像
暮雨
修改2018-11-26 14:52:57
6700
修改2018-11-26 14:52:57
举报
文章被收录于专栏:云端漫步云端漫步

原型在IT领域常被提及,那么什么是原型?就产品设计来举例吧,在产品开发中,产品经理需要根据业务,画出一个产品原型图,然后设计,根据产品原型图画出设计图,前端工程师根据设计图进行将设计图变为计算机可执行的代码。这大概是一个产品开发的流程。在这个体系中,原型是一个重要的存在。程序中的原型也是同样的意思。在此,原型有一个重要的概念,就是可以根据自身,构建出新的实例。在javascript就是基于原型实现继承的。

原型设计模式是一种重要的设计模式。go怎么实现这种复制。

先定义一个原型复制的接口

代码语言:go
复制
type Cloneable struct {
   Clone()  Cloneable
}

再实现一个原型管理器

代码语言:go
复制
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
}

来看完整代码实现

代码语言:go
复制
package main

import "fmt"

type Cloneable interface {
	Clone() Cloneable
}

type PrototypeManager struct {
	prototypes map[string]Cloneable
}

func NewPrototypeManager() *PrototypeManager {
	return &PrototypeManager{
		prototypes: make(map[string]Cloneable),
	}
}

func (m *PrototypeManager) Get(name string) Cloneable{
   return m.prototypes[name]
}

func (m *PrototypeManager) Set(name string, prototype Cloneable) {
   m.prototypes[name] = prototype
}

// 测试
type Person struct {
	name string
	age int
	height int
}

func (p *Person) Clone() Cloneable {
	person := *p
	return &person
}

func main() {
	manager := NewPrototypeManager()

	person := &Person{
		name: "zhangsan",
		age: 18,
		height: 175,
	}

	manager.Set("person", person)
	c := manager.Get("person").Clone()

	person1 := c.(*Person)

	fmt.Println("name:", person1.name)
	fmt.Println("age:", person1.age)
	fmt.Println("height:", person1.height)
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档