1. Singleton Pattern
Singleton creational design pattern restricts the instantiation of a type to a single object.
1.1. Implementation
package singleton
type singleton map[string]string
var (
once sync.Once
instance singleton
)
func New() singleton {
once.Do(func() {
instance = make(singleton)
})
return instance
}
1.2. Usage
s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])
// This is that
1.3. Rules of Thumb
- Singleton pattern represents a global state and most of the time reduces testability.