设计模式--原型(Prototype)模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式--原型(Prototype)模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模式定義
指原型實例指定創建對象的種類,并且通過拷貝這些原型創建新的對象
類圖
應用場景
當代碼不應該依賴于需要復制的對象的具體類時
優點
1.以不耦合具體類的情況下克隆對象;
2.避免重復的初始化代碼;
3.更方便的構建復雜對象;
要點總結
- Prototype模式同樣用于隔離類對象的使用者和具體類型(易變類)之間的耦合關系,它同樣要求這些“易變類”擁有“穩定的接口”
- Prototype模式對于“如何創建易變類的實體對象”采用“原型克隆”的方法來做,它使得我們可以非常靈活地動態創建“擁有某些穩定接口”的新對象–所需工作僅僅是注冊一個新類的對象(即原型),然后在任何需要的地方Clone
Go語言代碼實現
工程目錄
prototype.go
package ProtoType//原型對象需要實現的接口 type Cloneable interface {Clone() Cloneable }//原型對象的類 type ProtoTypeManger struct {Prototypes map[string]Cloneable }//構造初始化方法 func NewProtoTypeManger () * ProtoTypeManger {return &ProtoTypeManger{make(map[string]Cloneable)} }//抓取 func (p *ProtoTypeManger) Get (name string) Cloneable {return p.Prototypes[name] }//設置 func (p *ProtoTypeManger) Set (name string, prototype Cloneable) {p.Prototypes[name] = prototype }type1.go
package ProtoTypetype Type1 struct {name string }func (t * Type1) Clone() Cloneable {tc := *t //開辟內存新建變量,存儲指針指向的內容return &tc//return t }type2.go
package ProtoTypetype Type2 struct {name string }func (t * Type2) Clone() Cloneable {tc := *t //開辟內存新建變量,存儲指針指向的內容return &tc }prototype_test.go
package ProtoTypeimport ("fmt""testing" )func TestNewProtoTypeManger(t *testing.T) {mgr := NewProtoTypeManger()t1 := &Type1{name:"type1"}mgr.Set("t1", t1)t11 := mgr.Get("t1")t22 := t11.Clone()if t11 == t22 {fmt.Println("淺拷貝")} else {fmt.Println("深拷貝")} }總結
以上是生活随笔為你收集整理的设计模式--原型(Prototype)模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式--建造者(Builder)模式
- 下一篇: 设计模式--享元(Flyweight)模