add DCL singleton implement

This commit is contained in:
2022-12-03 21:37:16 +08:00
parent 7bca6fe5cf
commit c7f63caccc
3 changed files with 55 additions and 9 deletions

33
util/Singleton.go Normal file
View 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
}