Golang 单例模式的几种形式
1.非线程安全,虽然说是单例模式,但是如果实例正在创建中,此时多个线程同时访问,就会获得多个结果
package main
var instance *Singleton
type Singleton struct {
}
func Instance() *Singleton{
if instance == nil {
instance = &Singleton{}
}
return instance
}
- 加锁单例模式
package main
import "sync"
var (
instance *Singleton
mu sync.Mutex
)
type Singleton struct {
}
func Instance() *Singleton{
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &Singleton{}
}
return instance
}
以下是参考他人的方法。思路很好
3.避免了每次加锁,提高了代码效率
package main
import "sync"
var (
instance *Singleton
mu sync.Mutex
)
type Singleton struct {
}
func Instance() *Singleton {
if instance == nil {
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &Singleton{}
}
}
return instance
}
4.once
实现
package main
import "sync"
var (
instance *Singleton
once sync.Once
)
type Singleton struct {
}
func Instance() *Singleton {
once.Do(func() {
instance = &Singleton{}
})
return instance
}
有疑问加站长微信联系(非本文作者)