mirror of
https://github.com/tursom/GoCollections.git
synced 2026-08-19 05:23:29 +08:00
add DCL singleton implement
This commit is contained in:
33
util/Singleton.go
Normal file
33
util/Singleton.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package util
|
||||
|
||||
import "sync"
|
||||
|
||||
// Singleton DCL singleton implement
|
||||
type Singleton[T any] struct {
|
||||
value T
|
||||
init func() T
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func NewSingleton[T any](init func() T) *Singleton[T] {
|
||||
if init == nil {
|
||||
panic("nil singleton initializer")
|
||||
}
|
||||
|
||||
return &Singleton[T]{
|
||||
init: init,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Singleton[T]) Get() T {
|
||||
if s.init != nil {
|
||||
s.lock.Lock()
|
||||
s.lock.Unlock()
|
||||
if s.init != nil {
|
||||
s.value = s.init()
|
||||
s.init = nil
|
||||
}
|
||||
}
|
||||
|
||||
return s.value
|
||||
}
|
||||
Reference in New Issue
Block a user