[02]Go设计模式:原型模式(Prototype )

原型模式

1、简介

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

这种模式是实现了一个原型接口,该接口用于建立当前对象的克隆。当直接建立对象的代价比较大时,则采用这种模式。例如,一个对象须要在一个高代价的数据库操做以后被建立。可能每一个对象有大量相同的数据,这个时候咱们就能够缓存该对象,在下一个请求时返回它的克隆,仅须要更信部分不一样的数据,须要的时候更新数据入库,以此来减小数据库交互。数据库

2、代码实现

先定义一个原型复制的接口设计模式

type Cloneable interface {
   Clone()  Cloneable
}

实现Clone函数缓存

type Person struct {
	name string
	age int
	height int
}

func (p *Person) Clone() Cloneable {
	person := *p
	return &person
}

func(p *Person) SetName(name string) {
	p.Name = name
}

func(p *Person) SetAge(age int) {
	p.Age = age
}

来看完整代码实现函数

package main

import "fmt"

type Cloneable interface {
	Clone() Cloneable
}

type Person struct {
	Name string
	Age int
	Height int
}

func (p *Person) Clone() *Person {
	person := *p
	return &person
}

func(p *Person) SetName(name string) {
	p.Name = name
}

func(p *Person) SetAge(age int) {
	p.Age = age
}

func main() {

	p := &Person{
		Name: "zhang san",
		Age: 20,
		Height: 175,
	}

	p1 :=p.Clone()
	p1.SetAge(30)
	p1.SetName("Li Si")

	fmt.Println("name:", p1.Name)
	fmt.Println("age:", p1.Age)
	fmt.Println("height:", p1.Height)
}

输出结果:性能

name: Li si
age: 30
height: 175

完整代码地址:https://gitee.com/ncuzhangben/GoStudy/tree/master/go-design-pattern/02-Prototype设计

3、参考资料:

一、 https://cloud.tencent.com/developer/article/1366818code

相关文章
相关标签/搜索