https://blog.youkuaiyun.com/weixin_42366378/article/details/106010511?utm_source=app 面试考的一些
defer defer对变量和函数以及方法是不一样的,eg:defer a.add(a).add(a),谁会被丢弃
1、饿汉模式
type Instance struct {
}
var MyInstance = &Instance{}
func GetInstanc() *Instance {
return MyInstance
}
type Instance struct {
}
var MyInstance *Instance
//服务启动时加载
func init() {
MyInstance = &Instance{}
}
2、懒加载模式
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
}
3、sync.once方式
import (
"sync"
)
type singleton struct {
}
var instance *singleton
var once sync.Once
func GetInstance() *singleton {
//once.DO启动后只会执行一次
once.Do(func() {
instance = &singleton{}
})
return instance
}