Go语言中,实现单例模式的方式有很多种。单例模式确保一个类只有一个实例,并提供一个全局访问点。Go语言没有类的概念,但是可以通过结构体、函数和包级变量来实现类似的功能。
懒汉实现
type Product interface {DoSomething()
}type singletonProduct struct{}func (p *singletonProduct) DoSomething() {}var instanceOnce struct {instance Productonce sync.Once
}func GetInstance() Product {instanceOnce.once.Do(func() {instanceOnce.instance = &singletonProduct{}})return instanceOnce.instance
}
- singletonProduct使用小写开头,防止使用者自己创建实例,提供GetInstance方法作为获取实例的唯一入口。
- 使用sync.Once处理单次创建问题。
饿汉实现
package singletontype Product interface {DoSomething()
}type singletonProduct struct{}func (p *singletonProduct) DoSomething() {}var instance = &singletonProduct{}func GetInstance() Product {return instance
}
- 利用Go的包初始化机制,在程序启动时就创建实例。