设计模式-原型模式

原型模式

  • 原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

  • 这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式
    prototype.go

package prototype

type Prototype interface {
	Name() string
	Value() []int
	Clone() Prototype
}

type ProtoStruct struct {
	name  string
	value []int
}

func (p *ProtoStruct) Name() string {
	return p.name
}

func (p *ProtoStruct) Value() []int {
	return p.value
}

func (p *ProtoStruct) Clone() Prototype {
	//newValue := make([]int, len(p.value))
	//for index, value := range p.value{
	//	newValue[index] = value
	//}
	return &ProtoStruct{name: p.name, value: p.value}
}

prototype_test.go

package prototype

import (
	"fmt"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestProtoStruct_Clone(t *testing.T) {
	p := ProtoStruct{name: "haha", value: []int{1,2,3}}
	newP := p.Clone()
	p.value = append(p.value, 10)
	fmt.Println(p.value)
	fmt.Println(newP.Value())
	fmt.Println(assert.Equal(t, p.name, newP.Name()))
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值