Go 實現常用設計模式(一)單例模式

pibigstar發表於2019-09-07

意圖:
使程式執行期間只存在一個例項物件

1. 原始的單例模式

package singleton
import "sync"

var (
    instance *Instance
    lock     sync.Mutex
)

type Instance struct {
    Name string
}

// 雙重檢查
func GetInstance(name string) *Instance {
    if instance == nil {
        lock.Lock()
        defer lock.Unlock()
        if instance == nil {
            instance = &Instance{Name: name}
        }
    }
    return instance
}

2. Go語言風格的單例模式

package singleton

import "sync"

var (
    goInstance *Instance
    once       sync.Once
)

// 使用go 實現單例模式
func GoInstance(name string) *Instance {
    if goInstance == nil {
        once.Do(func() {
            goInstance = &Instance{
                Name: name,
            }
        })
    }
    return goInstance
}

其實就是使用 once.Do 來保證 某個物件只會初始化一次,有一點要要注意的是 這個 once.Do只會被執行一次,哪怕Do函式裡面的發生了異常,物件初始化失敗了,這個Do函式也不會被再次執行了

具體程式碼

更詳細的程式碼可參考:https://github.com/pibigstar/go-demo 裡面包含了Go常用的設計模式、Go面試易錯點、簡單的小專案(區塊鏈,爬蟲等)、還有各種第三方的對接(redis、sms、nsq、elsticsearch、alipay、oss...),如果對你有所幫助,請給個Star,你的支援,是我最大的動力!

相關文章