golang 單例模式的幾種實現

一、餓漢模式code

type Instance struct {

}

var MyInstance = &Instance{}

func GetInstanc() *Instance {
   return MyInstance
}
type Instance struct {

}

var MyInstance *Instance
//服務啓動時加載
func init() {
   MyInstance = &Instance{}
}

二、懶加載模式it

type singleton struct {
}

// private
var instance *singleton

// public
func GetInstance() *singleton {
    if instance == nil {
        instance = &singleton{}     // not thread safe
    }
    return instance
}
type singleton struct {
}

var instance *singleton
var mu sync.Mutex

func GetInstance() *singleton {
    mu.Lock()
    defer mu.Unlock()

    if instance == nil {
        instance = &singleton{}     
    }
    return instance
}

三、sync.once方式class

import (
    "sync"
)
 
type singleton struct {
}
 
var instance *singleton
var once sync.Once
 
func GetInstance() *singleton {
    //once.DO啓動後只會執行一次
    once.Do(func() {
        instance = &singleton{}
    })
    return instance
}
相關文章
相關標籤/搜索