Golang设计模式——13原型模式

原型模式

优点

  1. 原型模式简化了创建对象的过程,通过一个已有的实例进行复制提高了创建实例的效率,具有较好的可扩展性。

缺点

  1. 要注意深拷贝与浅拷贝

场景

  1. 原型模式适合于当一个类初始化需要消耗很多资源时,有很多相似对象时,可以设计一个原型,通过对成员变量的些微修改来实现;需要时可以用深克隆的方式保存对象的状态,比如实现撤销操作等。

代码

在这里插入图片描述

package Prototype

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

type ConcretePrototype struct {
	name string
}

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

func (p *ConcretePrototype) Clone() Prototype {
	return &ConcretePrototype{name: p.name}
}

package Prototype

import "testing"
import "github.com/stretchr/testify/assert"
func TestConcretePrototype_Clone(t *testing.T) {
	name:="wxf"
	p:=ConcretePrototype{name: name}
	newProto:=p.Clone()
	assert.Equal(t,name,newProto.Name())
}

其他设计模式

设计模式Git源代码
00简单工厂模式
01工厂方法模式
02抽象工厂模式
03外观模式
04建造者模式
05桥接模式
06命令模式
07迭代器模式
08模板模式
09访问者模式
10备忘录模式
11责任链模式
12中介模式
13原型模式
14状态模式
15策略模式
16享元模式
17组合模式
18解释器模式
19单例模式
20适配器模式
21代理模式
22装饰器模式
23观察者模式

posted @ 2021-09-25 15:07  cheems~  阅读(37)  评论(0编辑  收藏  举报