golang单例模式

一般写法

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
}

  

原文地址:https://www.cnblogs.com/wsw-seu/p/12857364.html