Go 设计模式 #
单例模式 #
常规 #
package singleton
import "sync"
var (
instance *Instance
lock sync.Mutex
)
type Instance struct {
Name string
}
// 双重检查
func GetInstance(name string) *Instance {
if instance == nil {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = &Instance{Name: name}
}
}
return instance
}
sync.Once #
package singleton
import "sync"
var (
goInstance *Instance
once sync.Once
)
func GoInstance(name string) *Instance {
if goInstance == nil {
once.Do(func() {
goInstance = &Instance{
Name: name,
}
})
}
return goInstance
}
叶王 © 2013-2020 版权所有。如果本文档对你有所帮助,可以请作者喝饮料。