How does one implement the Singleton design pattern in the go programming language?
You can do initialization using the once package:
This will ensure that your init methods only get called once.
Just put your variables and functions at the package level.
Also see similar question: How to make a singleton in Python
Easy peasy as you can see in the following code:
package main
import (
"fmt"
"sync"
)
type singleton struct {
count int
sync.RWMutex
}
var instance singleton
func GetInstance() *singleton {
return &instance
}
func (s *singleton) AddOne() {
s.Lock()
defer s.Unlock()
s.count++
}
func (s *singleton) GetCount() int {
s.RLock()
defer s.RUnlock()
return s.count
}
func main() {
obj1 := GetInstance()
obj1.AddOne()
fmt.Println(obj1.GetCount())
obj2 := GetInstance()
obj2.AddOne()
fmt.Println(obj2.GetCount())
obj3 := GetInstance()
obj3.AddOne()
fmt.Println(obj3.GetCount())
}
Expected result would be:
1 2 3
Because you're accessing to the same resource. That's the reason I've added mutex in order to be concurrent proven accessing count attribute from multiple processes. :-)
Source:
https://play.golang.org/p/2XnLztX8Gs5