美文网首页
设计模式——原型模式

设计模式——原型模式

作者: DevilRoshan | 来源:发表于2020-11-02 00:40 被阅读0次

什么是原型模式?

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

实现

type Prototype interface {
    Name() string
    Clone() Prototype
}

type ConcretePrototype struct {
    name string
}

func (this *ConcretePrototype) Name() string {
    return this.name
}

func (this *ConcretePrototype) Clone() Prototype {
    return &ConcretePrototype{name: this.name}
}
func TestConcretePrototypeClone(t *testing.T) {
    name := "laoyang"
    proto :=  ConcretePrototype{name:name}
    newProto := proto.Clone()
    assert.Equal(t, name, newProto.Name())
}
// === RUN   TestConcretePrototypeClone
// --- PASS: TestConcretePrototypeClone (0.00s)
// PASS

优点

  • 性能优良。不用重新初始化对象,而是动态地获取对象运行时的状态;
  • 逃避构造函数的约束。

缺点

  • 配置克隆方法需要对类的功能进行通盘考虑;

使用场景

  • 资源优化场景;
  • 性能和安全要求的场景;
  • 一个对象多个修改者的场景;
  • 一般与工厂方法模式一起出现,通过clone方法创建一个对象,然后由工厂方法提供给调用者。

相关文章

网友评论

      本文标题:设计模式——原型模式

      本文链接:https://www.haomeiwen.com/subject/ijmsvktx.html