Go Singleton Pattern 🎯

beginner
12 min

Go Singleton Pattern 🎯

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.

What is the Singleton Pattern? 📝

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.

Why Use the Singleton Pattern? 💡

  • Ensures that only one instance of a class is created. This can be useful for resources that are expensive to create or have global state.
  • Provides a global access point to the instance. This can simplify code that needs to interact with the instance, as there's no need to worry about creating the instance yourself.

How Does the Singleton Pattern Work in Go? 💡

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.

go
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.

Practical Example 🎯

Let's create a Logger singleton that logs messages to stdout.

go
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:

go
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 }

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🎉