文章目录
- 前言
- 代码
- 结果
- 总结
前言
本文章尝试使用go实现“原型”。
代码
package mainimport ("fmt")// 不同原型标志枚举type Type intconst (PROTOTYPE_1 Type = iotaPROTOTYPE_2)// 原型接口type IPrototype interface {Clone() IPrototypeMethod(value int)Print()}// 具体原型1type ConcretePrototype1 struct {namestringvalue int}// 构造函数func NewConcretePrototype1ByFields(name string, value int) *ConcretePrototype1 {return &ConcretePrototype1{name,value,}}func NewConcretePrototype1ByObject(cp *ConcretePrototype1) *ConcretePrototype1 {return &ConcretePrototype1{name:cp.name,value: cp.value,}}// 接口方法func (cp *ConcretePrototype1) Clone() IPrototype {return NewConcretePrototype1ByObject(cp)}func (cp *ConcretePrototype1) Method(value int) {cp.value = value}func (cp *ConcretePrototype1) Print() {fmt.Println("Call Method1 from ", cp.name, " with field : ", cp.value)}// 具体原型2type ConcretePrototype2 struct {namestringvalue int}// 构造函数func NewConcretePrototype2ByFields(name string, value int) *ConcretePrototype2 {return &ConcretePrototype2{name,value,}}func NewConcretePrototype2ByObject(cp *ConcretePrototype2) *ConcretePrototype2 {return &ConcretePrototype2{name:cp.name,value: cp.value,}}// 接口方法func (cp *ConcretePrototype2) Clone() IPrototype {return NewConcretePrototype2ByObject(cp)}func (cp *ConcretePrototype2) Method(value int) {cp.value = value}func (cp *ConcretePrototype2) Print() {fmt.Println("Call Method2 from ", cp.name, " with field : ", cp.value)}// 原型工厂type PrototypeFactory struct {prototypes map[Type]IPrototype}func NewPrototypeFactory() *PrototypeFactory {return &PrototypeFactory{prototypes: map[Type]IPrototype{PROTOTYPE_1: NewConcretePrototype1ByFields("PROTOTYPE_1 ", 1),PROTOTYPE_2: NewConcretePrototype2ByFields("PROTOTYPE_2 ", 2),},}}func (p *PrototypeFactory) CreatePrototype(t Type) IPrototype {return p.prototypes[t].Clone()}// 客户端代码func clientCode(p *PrototypeFactory) {fmt.Println("Let's create a Prototype 1")prototype1 := p.CreatePrototype(PROTOTYPE_1)prototype2 := p.CreatePrototype(PROTOTYPE_1)prototype1.Method(3)prototype2.Method(4)prototype1.Print()prototype2.Print()fmt.Println()fmt.Println("Let's create a Prototype 2")prototype1 = p.CreatePrototype(PROTOTYPE_2)prototype2 = p.CreatePrototype(PROTOTYPE_2)prototype1.Method(5)prototype2.Method(6)prototype1.Print()prototype2.Print()}func main() {clientCode(NewPrototypeFactory())}
结果
Let's create a Prototype 1Call Method1 fromPROTOTYPE_1 with field :3Call Method1 fromPROTOTYPE_1 with field :4Let's create a Prototype 2Call Method2 fromPROTOTYPE_2 with field :5Call Method2 fromPROTOTYPE_2 with field :6
总结
新人设计模式理解,望大家多多指点。