go知识重新整理

This commit is contained in:
Estom
2021-09-03 05:34:34 +08:00
parent 62309f856a
commit 1bad082e49
291 changed files with 29345 additions and 2 deletions

View File

@@ -0,0 +1,27 @@
package proto
//原型模式:使对象能复制自身,并暴露到接口中,使客户端面向接口编程时,不知道接口实际对象的情况下可以生成新的对象
//原型模式配合管理器使用,通过接口管理器可以在客户端不知道具体类型的情况下,得到新的实例,并且包含部分预设的配置
type Cloneable interface {
Clone() Cloneable
}
//
func NewProtoManager() *ProtoManager {
return &ProtoManager{
protos: make(map[string]Cloneable),
}
}
type ProtoManager struct {
protos map[string]Cloneable
}
func (p *ProtoManager) Get(name string) Cloneable {
return p.protos[name]
}
func (p *ProtoManager) Set(name string, proto Cloneable) {
p.protos[name] = proto
}

View File

@@ -0,0 +1,56 @@
/**
* @Author:zhoutao
* @Date:2020/12/13 上午11:48
* @Desc:
*/
package proto
import "testing"
var manager *ProtoManager
//
type Type1 struct {
name string
}
func (t *Type1) Clone() Cloneable {
//将值放进新的地址中
tc := *t
return &tc
}
//
type Type2 struct {
name string
}
func (t *Type2) Clone() Cloneable {
//将值放进新的地址中
tc := *t
return &tc
}
func TestClone(t *testing.T) {
t1 := manager.Get("t1")
t2 := t1.Clone()
if t1 == t2 {
t.Fatal("error, get clone do not working")
}
}
func TestCloneFromManager(t *testing.T) {
c := manager.Get("t1").Clone()
t1 := c.(*Type1)
if t1.name != "type1" {
t.Fatal("error!")
}
}
func init() {
manager = NewProtoManager()
t1 := &Type1{
name: "type1",
}
manager.Set("t1", t1)
}