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) } 複製程式碼