go设计模式之原型模式

栏目: Go · 发布时间: 6年前

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

以上所述就是小编给大家介绍的《go设计模式之原型模式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

500 Lines or Less

500 Lines or Less

Amy Brown、Michael DiBernardo / 2016-6-28 / USD 35.00

This book provides you with the chance to study how 26 experienced programmers think when they are building something new. The programs you will read about in this book were all written from scratch t......一起来看看 《500 Lines or Less》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具