The singleton — object oriented design pattern in golang

Compared to languages that feature classes — golang has its own approach on implementing object oriented design patterns. In this blogpost I will outline on how to imlement a typical object oriented design pattern in golang — the singleton.

What is the singleton pattern?

// global variablevar state string = "off"func start() { 
if state == "off" {
//do something
state == "on"
}
}
func stop() {
if state == "on" {
//do something
state == "off"
}
}
// singleton// no global variable here!func start() {
sm := statemanager.GetManager()
if sm.GetState() == "off" {
//do something
sm.SetState("on")
}
}
func stop() {
sm := statemanager.GetManager()
if sm.GetState() == "on" {
//do something
sm.SetState("off")
}
}

How to implement the singleton pattern in golang?

One great thing about golang is that it tries to stay away from special keywords to implement most functionallity and tries to let the user implement functinallity by combining basic services that the standard library offers. This allows easy modification and drop in replacement of individual code parts without the need to rewrite everything.

package statemanagertype manager struct {
state string
}
var singleton *manager
var once sync.Once
func GetManager() *manager {
once.Do(func() {
singleton = &manager{state: "off"}
})
return singleton
}
func (sm *manager) GetState() string {
return sm.state
}
func (sm *manager) SetState(s string) {
sm.state = s
}

Conclusion

In a nutshell the singleton moves a global variable into an encapsulated package. It is straightforward to implement a singleton in golang by combining basic struct functionallity with the sync.Once type.

Tech Consultant in Munich.