Go的單例模式

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

單例模式是一種常用的軟體設計模式。在它的核心結構中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統中一個類只有一個執行個體而且該執行個體易於外界訪問,從而方便對執行個體個數的控制並節約系統資源。如果希望在系統中某個類的對象只能存在一個,單例模式是最好的解決方案。

1.Go實現非安全執行緒的單例模式(懶漢 就是很懶的單例 哈哈):

package singletontype singleton struct {}var instance *singletonfunc GetInstance() *singleton {if instance == nil {instance = &singleton{} // <--- NOT THREAD SAFE}return instance}
12345678910111213 package singleton type singleton struct {} var instance *singleton func GetInstance() *singleton {if instance == nil {instance = &singleton{}   // <--- NOT THREAD SAFE}return instance}

非安全執行緒的單例模式是大家用得最多的一種。在Github上面的開源項目有很多都使用了非安全執行緒的。

這種寫法lazy loading很明顯,但是致命的是在多線程不能正常工作。

2.Go實現帶線程鎖的單例模式

var mu Sync.Mutexfunc GetInstance() *singleton { mu.Lock() // <--- Unnecessary locking if instance already created defer mu.Unlock() if instance == nil { instance = &singleton{} } return instance}
1234567891011 var mu Sync.Mutex func GetInstance() *singleton {    mu.Lock()                    // <--- Unnecessary locking if instance already created    defer mu.Unlock()     if instance == nil {        instance = &singleton{}    }    return instance}

這裡用了Go的

Sync.Mutex
1 Sync.Mutex

sync/mutex是Go語言底層基礎對象之一,用於構建多個goroutine間的同步邏輯,因此被大量高層對象所使用。
其工作模型類似於Linux核心的futex對象,具體實現極為簡潔,效能也有保證。

mutex對象僅有兩個數值欄位,分為為state(儲存狀態)和sema(用於計算休眠goroutine數量的訊號量)。
初始化時填入的0值將mutex設定在未鎖定狀態,同時保證時間開銷最小。
這一特性允許將mutex作為其它對象的子物件使用。

3.帶檢查鎖的的單例模式

func GetInstance() *singleton { if instance == nil { // <-- Not yet perfect. since it's not fully atomic mu.Lock() defer mu.Unlock() if instance == nil { instance = &singleton{} } } return instance}
1234567891011 func GetInstance() *singleton {    if instance == nil {     // <-- Not yet perfect. since it's not fully atomic        mu.Lock()        defer mu.Unlock()         if instance == nil {            instance = &singleton{}        }    }    return instance}

這是一個不錯的方法,但是還並不是很完美。因為編譯器最佳化沒有檢查執行個體儲存狀態。如果使用sync/atomic包的話 就可以自動幫我們載入和設定標記。

import "sync"import "sync/atomic"var initialized uint32...func GetInstance() *singleton { if atomic.LoadUInt32(&initialized) == 1 {return instance} mu.Lock() defer mu.Unlock() if initialized == 0 { instance = &singleton{} atomic.StoreUint32(&initialized, 1) } return instance}
12345678910111213141516171819202122 import "sync"import "sync/atomic" var initialized uint32... func GetInstance() *singleton {     if atomic.LoadUInt32(&initialized) == 1 {return instance}     mu.Lock()    defer mu.Unlock()     if initialized == 0 {         instance = &singleton{}         atomic.StoreUint32(&initialized, 1)    }     return instance}

 

個人覺得比較好的在go中使用單例設計的是這種

package singletonimport ( "sync")type singleton struct {}var instance *singletonvar once sync.Oncefunc GetInstance() *singleton { once.Do(func() { instance = &singleton{} }) return instance}
123456789101112131415161718 package singleton import (    "sync") type singleton struct {} var instance *singletonvar once sync.Once func GetInstance() *singleton {    once.Do(func() {        instance = &singleton{}    })    return instance}

通過使用sync.Once 包可以實現安全執行緒的單例模式。

如果寫得有什麼不對地方歡迎指出。

Go的單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.