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
}
相关文章
相关标签/搜索