1. 程式人生 > >go 設計模式(一)單例模式

go 設計模式(一)單例模式

go 的單例模式寫法比較簡單,可以通過sync.Once來輔助。

type Singleton struct {
    name string
}

var (
    once     sync.Once
    instance *Singleton
)

func New() *Singleton {
    once.Do(func() { // once.Do 呼叫的函式只執行 1 次
        instance = &Singleton{name: "Tom"}
    })
    return instance
}

測試程式碼:

func TestNew
(t *testing.T) { instance := New() instance2 := New() if instance != instance2 { t.Errorf("Get %p, Expect %p", instance2, instance) } }

我們來看看 once.Do 都做了什麼

type Once struct {
    m    Mutex
    done uint32
}

func (o *Once) Do(f func()) {
    if atomic.LoadUint32(&o.
done) == 1 { return } o.m.Lock() defer o.m.Unlock() if o.done == 0 { defer atomic.StoreUint32(&o.done, 1) f() } }

可以看到只有在 done 等於 0 的時候才呼叫 f(),一旦呼叫後 done 的值被置為 1