In software engineering, the Singleton pattern is a software design pattern that restricts the instantiation of a type to one object. This is useful when exactly one object is needed to coordinate actions across the system. In this article, we will discuss how to implement the Singleton pattern in Golang with an example code.
Singleton Pattern in Golang
The Singleton pattern is implemented in Golang using a struct type and a private package-level variable that holds the only instance of the struct. The struct’s constructor function is exported and is used to return the instance of the struct. Here is an example implementation of the Singleton pattern in Golang:
package singleton
type Singleton struct {
name string
}
var instance *Singleton
func GetInstance() *Singleton {
if instance == nil {
instance = &Singleton{name: "Golang Singleton"}
}
return instance
}
func (s *Singleton) GetName() string {
return s.name
}
In the above implementation, we have defined a struct type Singleton
with a single field name
. We have also declared a private package-level variable named instance
of type *Singleton
. The GetInstance()
function returns the instance of the Singleton
struct. If the instance
is nil
, it creates a new instance of the Singleton
struct and assigns it to the instance
…