原型模式(Prototype Pattern)

153 阅读1分钟

简述

原型模式(Prototype Pattern)属于创建型模式,用于创建重复的对象。在我们日常的开发过程中,往往会遇到一些场景需要大量的相同对象或创建对象的成本比较高,如果不使用原型模式,我们往往会新建一个对象,然后遍历对象中的所有属性赋值给另外一个对象,这里存在明显的缺点:1、使用者必须知道对象的实现细节,导致代码间耦合 2、一些私有的属性无法进行复制

应用

对象的拷贝

实现

  • 定义原型模式的接口和clone方法 type Prototype interface { Clone() Prototype }
  • struct实例实现clone方法,clone方法实现对实例的复制

示例

原型模式定义

package prototype

// 定义原型接口
type Prototype interface {
   Clone() Prototype
}

type Event struct {
   Name string
}

// 实现原型的接口
func (e *Event) Clone() Prototype {
   event := *e
   return &event
}

调用原型模式

package main

import (
   "github.com/design/pattern/prototype"
)

func main() {
   // 原型模式
   prototypeEvent := prototype.Event{
      Name: "原型模式",
   }
   newPrototypeEvent := prototypeEvent.Clone().(*prototype.Event)
}