在Go语言中,单例模式可以通过以下几种方式来实现:
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
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 mu sync.Mutex
func GetInstance() *Singleton {
if instance == nil {
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &Singleton{}
}
}
return instance
}
package singleton
import (
"sync"
"time"
)
type Singleton struct {}
var pool sync.Pool
var once sync.Once
func GetInstance() *Singleton {
once.Do(func() {
pool.New = func() interface{} {
return &Singleton{}
}
})
return pool.Get().(*Singleton)
}
func (s *Singleton) Put() {
pool.Put(s)
}
func main() {
s := GetInstance()
defer s.Put()
time.Sleep(time.Second)
}
以上是几种常见的单例模式实现方式,每种方式都有其特点和适用场景,具体选择哪种方式取决于实际需求。