Here is an example in Go for a package:
package main
import (
"fmt"
"sync"
)
var (
instance *Singleton
once sync.Once
)
type Singleton struct {
Data string
}
func GetSingleton() *Singleton {
once.Do(func() {
instance = &Singleton{
Data: "",
}
})
return instance
}
func main() {
s := GetSingleton()
fmt.Printf("Print 1: %s\n", s.Data)
s.Data = "Cron"
s = GetSingleton()
fmt.Printf("Print 2: %s\n", s.Data)
s.Data = "Deux"
s = GetSingleton()
fmt.Printf("Print 3: %s\n", s.Data)
s.Data = "Tres"
s = GetSingleton()
fmt.Printf("Print 4: %s\n", s.Data)
}
// Output:
// Print 1:
// Print 2: Cron
// Print 3: Deux
// Print 4: Tres
Usually, singleton requires the synchronized creation. You only need to synchronize the creation once and save the creation into a global variable. Then, at every needs, you just call in the global variable and use it.