内容简介:原型在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设计模式之原型模式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 设计模式——订阅模式(观察者模式)
- 设计模式-简单工厂、工厂方法模式、抽象工厂模式
- java23种设计模式-门面模式(外观模式)
- 设计模式-享元设计模式
- Java 设计模式之工厂方法模式与抽象工厂模式
- JAVA设计模式之模板方法模式和建造者模式
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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》 这本书的介绍吧!