Junior
Tell me 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. In Go, it is usually implemented using the sync package (sync.Once) to ensure thread safety.
Pros:
- Controlled access to the single instance.
- Helps save resources by avoiding the creation of multiple identical objects.
Cons:
- Can make testing difficult due to global state.
- Violates the single responsibility principle, as the class manages its own creation.
Implementation in Go using sync.Once:
package singleton
import (
"fmt"
"sync"
)
// singleton represents the single instance of the object.
type singleton struct {
value string
}
// once ensures the code runs only once.
var once sync.Once
// instance holds the single instance of singleton.
var instance *singleton
// GetInstance returns the single instance of singleton.
func GetInstance() *singleton {
once.Do(func() {
instance = &singleton{value: "I am the only instance!"}
fmt.Println("Created the singleton instance.")
})
return instance
}
// SomeMethod is an example method of singleton.
func (s *singleton) SomeMethod() {
fmt.Println("Called the singleton method:", s.value)
}