The schema definition

A stereotype instance specifies the types of objects to be created and creates new objects by copying these stereotypes

The class diagram

Application scenarios

When the code should not depend on the concrete class of the object that needs to be copied

advantages

1. Clone objects without coupling concrete classes;

2. Avoid duplicate initialization code;

3. More convenient to construct complex objects;

The point to summarize

  • The Prototype pattern is also used to isolate the coupling between the user of a class object and the concrete type (mutable classes). It also requires that these “mutable classes” have a “stable interface”.
  • The Prototype pattern takes a “Prototype Clone” approach to “how to create entity objects of mutable classes”. It makes it very flexible to dynamically create new objects “with some stable interface” — the job is simply to register an object of a new class (that is, a Prototype) and Clone it anywhere you need it

Go language code implementation

Project directory

prototype.go

Package Prototype type Cloneable interface {Clone() Cloneable} // Type PrototypeManger struct { // func newPrototypeManger () * PrototypeManger {return &prototypemanger {make(map[string]Cloneable)}} // grab func (p *ProtoTypeManger) Get (name string) Cloneable {return P.rototypes [name]} Set func (p *ProtoTypeManger) Set (name string, prototype Cloneable) { p.Prototypes[name] = prototype }

type1.go

Package ProtoType type Type1 struct {name string} func (t * Type1) Clone() Cloneable {tc := *t Return &tc //return t}

type2.go

Package ProtoType type Type2 struct {name string} func (t * Type2) Clone() Cloneable {tc := *t Return &tc}

prototype_test.go

package ProtoType import ( "fmt" "testing" ) func TestNewProtoTypeManger(t *testing.T) { mgr := NewProtoTypeManger() t1 := &Type1{name:"type1"} mgr.Set("t1", T11 := MGR.Get("t1") t11 := t11.Clone() if t11 == t22 {FMT.Println(" deep copy ")} else {FMT.Println(" deep copy ")}}