github.com/tursom/GoCollections@v0.3.10/util/Singleton.go (about)

     1  package util
     2  
     3  import "sync"
     4  
     5  // Singleton DCL singleton implement
     6  type Singleton[T any] struct {
     7  	value T
     8  	init  func() T
     9  	lock  sync.Mutex
    10  }
    11  
    12  func NewSingleton[T any](init func() T) *Singleton[T] {
    13  	if init == nil {
    14  		panic("nil singleton initializer")
    15  	}
    16  
    17  	return &Singleton[T]{
    18  		init: init,
    19  	}
    20  }
    21  
    22  func (s *Singleton[T]) Get() T {
    23  	if s.init != nil {
    24  		s.lock.Lock()
    25  		s.lock.Unlock()
    26  		if s.init != nil {
    27  			s.value = s.init()
    28  			s.init = nil
    29  		}
    30  	}
    31  
    32  	return s.value
    33  }