区块链的征程已开启
单例模式
Java中的单例模式的实现可以有饿汉式、懒汉式、双锁、静态内部类、枚举等形式,在go中如何实现单例呢,先来最简单的形式,不考虑高并发的情况下,应该怎样实现
package main
var m *Singleton
type Singleton struct {
}
func GetInstance() *Singleton {
if m == nil {
m = &Singleton{}
}
return m
}
问题就是并发的时候会取到多个对象,解决方案
加锁
package main
import (
"sync"
)
var instance *Singleton
var lock *sync.Mutex = &sync.Mutex{}
type Singleton struct {
}
func GetInstance() *Singleton {
lock.Lock()
defer lock.Unlock()
if instance != nil {
instance = &Singleton{}
}
return instance
}
go语言特性,支持一种更为方便的加锁:sync.Once
package main
import (
"sync"
)
var (
instance *Singleton
lock *sync.Mutex = &sync.Mutex{}
once sync.Once
)
type Singleton struct {
}
func GetInstance() *Singleton {
once.Do(func() {
instance = &Singleton{}
})
return instance
}
有疑问加站长微信联系(非本文作者)