https://blog.csdn.net/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