Junior
Tell us about the Singleton design pattern.
sobes.tech AI
Answer from AI
The Singleton design pattern guarantees that a class has only one instance and provides a global point of access to it.
Pros:
- Controlled access to the single instance.
- Saves resources when creating a costly object.
- Allows access to the instance from anywhere in the program.
Cons:
- Violates the single responsibility principle (the class is responsible for both logic and managing its instance).
- Can make testing difficult (hard to replace the "singleton" with a mock).
- Creates tight coupling in the code.
Implementations in Golang:
Thread-safe implementation using sync.Once:
package main
import (
"fmt"
"sync"
)
type singleton struct{}
var instance *singleton
var once sync.Once
func GetInstance() *singleton {
once.Do(func() {
instance = &singleton{}
fmt.Println("Singleton instance created") // For demonstration
})
return instance
}
func main() {
s1 := GetInstance()
s2 := GetInstance()
if s1 == s2 {
fmt.Println("Both instances are the same")
} else {
fmt.Println("Instances are different")
}
}
This implementation guarantees that initialization (creation of the instance) occurs only once, even with parallel calls to GetInstance. sync.Once is the most preferred way to implement Singleton in Golang.