Golang设计模式之原型模式

Jackey Golang 1,824 次浏览 , , 没有评论
package main

import "fmt"

// 原型对象需要实现的接口
// copy 原有的对象
type Cloneable interface {
    Clone() Cloneable
}

// 原型的类
type PrototypeManager struct {
    prototypes map[string]Cloneable
}

// 构造初始化
func NewPrototypeManager() *PrototypeManager {
    return &PrototypeManager{make(map[string]Cloneable)}
}

// 抓取
func (p *PrototypeManager) Get(name string) Cloneable {
    return p.prototypes[name]
}

// 设置
func (p *PrototypeManager) Set(name string, cloneable Cloneable) {
    p.prototypes[name] = cloneable
}

type Type1 struct {
    name string
}

func (t *Type1) Clone() Cloneable {
    //tc := *t
    //return &tc // 深复制
    return t // 浅复制
}

type Type2 struct {
    name string
}

func (t *Type2) Clone() Cloneable {
    tc := *t   // 开辟内存新建变量,存储指针指向的内容
    return &tc // 返回地址
}

func main() {
    mgr := NewPrototypeManager()
    t1 := &Type1{name: "type1"}
    mgr.Set("t1", t1)
    t11 := mgr.Get("t1")
    fmt.Println(t11)
    t22 := t11.Clone() // 复制
    if t11 == t22 {
        fmt.Println("浅复制")
    } else {
        fmt.Println("深复制")
    }
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go