什么是原型模式?
- 原型模式即通过复制生成实例
- 当对象种类繁多,无法将它们整合到一个类时或难以根据类生成实例时或希望与生成的实例解耦时,可以使用原型模式
示范代码(prototype.go)
package Prototype
type Prototype interface {
Name() string
Clone() Prototype
}
type ConcretePrototype struct {
Prototype
name string
}
func (p *ConcretePrototype) Name() string {
return p.name
}
func (p *ConcretePrototype) Clone() Prototype {
return &ConcretePrototype{name: p.name}
}
测试用例(prototype_test.go)
package Prototype
import (
"fmt"
"testing"
)
func TestConcretePrototype_Clone(t *testing.T) {
p := &ConcretePrototype{
name: "ConcretePrototype",
}
p2 := p.Clone()
fmt.Println(p.name == p2.Name())
}