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

原型模式

一、简介

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

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

二、代码实现

先定义一个原型复制的接口

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

三、参考资料:

1、 https://cloud.tencent.com/developer/article/1366818

猜你喜欢

转载自www.cnblogs.com/0pandas0/p/12038136.html