github.com/songzhibin97/gkit@v1.2.13/container/group/group.go (about) 1 package group 2 3 import "sync" 4 5 // package group: 提供懒加载容器 6 7 // Group 懒加载容器 8 type Group struct { 9 sync.RWMutex 10 f func() interface{} 11 objs map[string]interface{} 12 } 13 14 // Get 根据key 获取 value 15 func (g *Group) Get(key string) interface{} { 16 g.RLock() 17 if obj, ok := g.objs[key]; ok { 18 g.RUnlock() 19 return obj 20 } 21 g.RUnlock() 22 23 g.Lock() 24 defer g.Unlock() 25 // 再次判断 26 if obj, ok := g.objs[key]; ok { 27 return obj 28 } 29 30 obj := g.f() 31 g.objs[key] = obj 32 return obj 33 } 34 35 // ReSet 更换实例化函数 36 func (g *Group) ReSet(nf func() interface{}) { 37 if nf == nil { 38 panic("container.group: 不能为新函数分配nil") 39 } 40 g.Lock() 41 g.f = nf 42 g.Unlock() 43 g.Clear() 44 } 45 46 func (g *Group) Clear() { 47 g.Lock() 48 defer g.Unlock() 49 g.objs = make(map[string]interface{}) 50 } 51 52 // NewGroup Group 实例化方法 53 func NewGroup(f func() interface{}) LazyLoadGroup { 54 if f == nil { 55 panic("container.group: 不能为新函数分配nil") 56 } 57 return &Group{ 58 f: f, 59 objs: make(map[string]interface{}), 60 } 61 }