Welcome to our deep dive into the Go Singleton Pattern! In this lesson, we'll learn how to create unique, globally accessible instances of a class in Go.
The Singleton Pattern is a design pattern that ensures a class has only one instance, and provides a global point of access to it. It's useful when you need to control access to an object that should be instantiated only once, and provide a global access point to it.
In Go, the Singleton Pattern is often implemented using a single, exported function that returns the singleton instance. This function initializes the singleton instance lazily, the first time it's called.
type Singleton struct {
data string
}
var instance *Singleton
func GetInstance() *Singleton {
if instance == nil {
instance = &Singleton{"Instance created"}
}
return instance
}In the above example, the GetInstance function returns the singleton instance. If the instance doesn't exist, it creates a new one and stores it in the instance variable.
Let's create a Logger singleton that logs messages to stdout.
type Logger struct{}
var logger *Logger
func GetLogger() *Logger {
if logger == nil {
logger = &Logger{}
}
return logger
}
func (l *Logger) Log(msg string) {
fmt.Println("Logger:", msg)
}Now, you can use the Logger singleton like this:
func main() {
logger1 := GetLogger()
logger1.Log("First logger instance")
logger2 := GetLogger()
logger2.Log("Second logger instance")
// Both logger1 and logger2 point to the same instance
fmt.Println(logger1 == logger2) // prints: true
}Why does the above code output `true` when comparing `logger1` and `logger2`?
That's it for our introduction to the Go Singleton Pattern! As you see, it's a powerful tool for managing global resources in Go. Happy coding! 🎉