go设计模式之原型模式

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

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

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

type Cloneable struct {
   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 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)
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值