github.com/szq-123/codingpractice@v0.0.0-20240430111904-2778dfaf7994/golang/coding/design_pattern/Singleton.go (about)

     1  package design_pattern
     2  
     3  /*
     4  单例模式
     5  	某个类只有一个实例,且自行实例化并向整个系统提供此实例
     6  
     7  你可以直接使用封装好的 sync.Once() 方法,实现单例模式
     8  */
     9  
    10  import (
    11  	"sync"
    12  	"sync/atomic"
    13  )
    14  
    15  // Once 线程安全
    16  type Once struct {
    17  	Done uint32
    18  	sync.Mutex
    19  }
    20  
    21  func (o *Once) Do(f func()) {
    22  	if atomic.LoadUint32(&o.Done) == 1 {
    23  		return
    24  	}
    25  
    26  	o.Lock()
    27  	defer o.Unlock()
    28  
    29  	if o.Done == 0 {
    30  		defer atomic.AddUint32(&o.Done, 1)
    31  		f()
    32  	}
    33  }
    34  
    35  type SingleExample struct{}
    36  
    37  var (
    38  	once     Once
    39  	instance *SingleExample
    40  )
    41  
    42  func Instance() *SingleExample {
    43  	once.Do(func() {
    44  		instance = new(SingleExample)
    45  	})
    46  	return instance
    47  }