在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)
}
以上是幾種常見的單例模式實現方式,每種方式都有其特點和適用場景,具體選擇哪種方式取決于實際需求。