一般写法

type singleton struct{
}
var mu sync.Mutex
var instance *singleton
func GetInstance() *singleton{
	if instance == nil{
		mu.Lock()
		defer mu.Unlock()
		if instance == nil{
			instance = &singleton{}
		}
	}
	return instance
}

go 中更好的写法

type singleton struct {
}

var instance *singleton
var once sync.Once
func GetInstance() *singleton{
	once.Do(func(){
		instance = &singleton{}
	})
	return instance
}

  

相关文章:

  • 2021-07-15
  • 2023-01-11
  • 2021-09-21
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
相关资源
相似解决方案