Go 实现常用设计模式(一)单例模式
单例 (singleton)
意图:
使程序运行期间只存在一个实例对象
1. 原始的单例模式
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
}
2. Go语言风格的单例模式
package singleton
import "sync"
var (
goInstance *Instance
once sync.Once
)
// 使用go 实现单例模式
func GoInstance(name string) *Instance {
if goInstance == nil {
once.Do(func() {
goInstance = &Instance{
Name: name,
}
})
}
return goInstance
}
其实就是使用
once.Do
来保证 某个对象只会初始化一次,有一点要要注意的是 这个 once.Do只会被运行一次,哪怕Do函数里面的发生了异常,对象初始化失败了,这个Do函数也不会被再次执行了
具体代码
更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了Go常用的设计模式、Go面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个Star
,你的支持,是我最大的动力!
本作品采用《CC 协议》,转载必须注明作者和本文链接
很多东西不是会了才能做,而是做了才能学会 (赞~)