Practice singleton

Signed-off-by: Bruce <weichou1229@gmail.com>
This commit is contained in:
Bruce 2019-02-10 21:59:57 +08:00
parent 58b864507c
commit 01aad3573b
No known key found for this signature in database
GPG Key ID: C715526B381CAF28
2 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package internal
import (
"fmt"
"sync"
)
// singleton is private struct, it should be created and fetched by GetSingletonObject func
type singleton struct {
}
func (singleton) SayHi() {
fmt.Println("Hi!")
}
var (
once sync.Once
instance singleton
)
func GetSingletonObject() singleton {
once.Do(func() {
instance = singleton{}
})
return instance
}

View File

@ -0,0 +1,10 @@
package main
import (
"github.com/weichou1229/go-patterns/playground/singleton/internal"
)
func main() {
var s = internal.GetSingletonObject()
s.SayHi()
}