Go語(yǔ)言中的單例模式可以通過(guò)以下幾種方式來(lái)實(shí)現(xiàn):
package singleton
type singleton struct {
// ...
}
var instance *singleton
func init() {
instance = &singleton{
// ...
}
}
func GetInstance() *singleton {
return instance
}
package singleton
import "sync"
type singleton struct {
// ...
}
var instance *singleton
var once sync.Once
func GetInstance() *singleton {
once.Do(func() {
instance = &singleton{
// ...
}
})
return instance
}
package singleton
import "sync"
type singleton struct {
// ...
}
var instance *singleton
var mutex sync.Mutex
func GetInstance() *singleton {
mutex.Lock()
defer mutex.Unlock()
if instance == nil {
instance = &singleton{
// ...
}
}
return instance
}
這些實(shí)現(xiàn)方法都可以保證只有一個(gè)實(shí)例對(duì)象,并且在需要使用該對(duì)象時(shí)提供統(tǒng)一的訪問(wèn)入口。