Singleton in go
Solution 1:
Setting aside the argument of whether or not implementing the singleton pattern is a good idea, here's a possible implementation:
package singleton
type single struct {
O interface{};
}
var instantiated *single = nil
func New() *single {
if instantiated == nil {
instantiated = new(single);
}
return instantiated;
}
single
and instantiated
are private, but New()
is public. Thus, you can't directly instantiate single
without going through New()
, and it tracks the number of instantiations with the private boolean instantiated
. Adjust the definition of single
to taste.
However, as several others have noted, this is not thread-safe, unless you're only initializing your singleton in init()
. A better approach would be to leverage sync.Once
to do the hard work for you:
package singleton
import "sync"
type single struct {
O interface{};
}
var instantiated *single
var once sync.Once
func New() *single {
once.Do(func() {
instantiated = &single{}
})
return instantiated
}
See also, hasan j's suggestion of just thinking of a package as a singleton. And finally, do consider what others are suggesting: that singletons are often an indicator of a problematic implementation.
Solution 2:
The best approach will be:
package singleton
import "sync"
type singleton struct {
}
var instance *singleton
var once sync.Once
func GetInstance() *singleton {
once.Do(func() {
instance = &singleton{}
})
return instance
}
You should read this Link
Solution 3:
Just put your variables and functions at the package level.
Also see similar question: How to make a singleton in Python
Solution 4:
I think that in a concurrent world we need to be a bit more aware that these lines are not executed atomically:
if instantiated == nil {
instantiated = new(single);
}
I would follow the suggestion of @marketer and use the package "sync"
import "sync"
type MySingleton struct {
}
var _init_ctx sync.Once
var _instance *MySingleton
func New() * MySingleton {
_init_ctx.Do( func () { _instance = new(MySingleton) } )
return _instance
}