mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-22 04:36:02 +03:00
Practice singleton
Signed-off-by: Bruce <weichou1229@gmail.com>
This commit is contained in:
parent
58b864507c
commit
01aad3573b
27
playground/singleton/internal/singleton.go
Normal file
27
playground/singleton/internal/singleton.go
Normal 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
|
||||
}
|
10
playground/singleton/main.go
Normal file
10
playground/singleton/main.go
Normal file
@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/weichou1229/go-patterns/playground/singleton/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var s = internal.GetSingletonObject()
|
||||
s.SayHi()
|
||||
}
|
Loading…
Reference in New Issue
Block a user