From 01aad3573b7a9fd2f125c2170a571145a9d9f54e Mon Sep 17 00:00:00 2001 From: Bruce Date: Sun, 10 Feb 2019 21:59:57 +0800 Subject: [PATCH] Practice singleton Signed-off-by: Bruce --- playground/singleton/internal/singleton.go | 27 ++++++++++++++++++++++ playground/singleton/main.go | 10 ++++++++ 2 files changed, 37 insertions(+) create mode 100644 playground/singleton/internal/singleton.go create mode 100644 playground/singleton/main.go diff --git a/playground/singleton/internal/singleton.go b/playground/singleton/internal/singleton.go new file mode 100644 index 0000000..804794c --- /dev/null +++ b/playground/singleton/internal/singleton.go @@ -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 +} diff --git a/playground/singleton/main.go b/playground/singleton/main.go new file mode 100644 index 0000000..a1ec7ad --- /dev/null +++ b/playground/singleton/main.go @@ -0,0 +1,10 @@ +package main + +import ( + "github.com/weichou1229/go-patterns/playground/singleton/internal" +) + +func main() { + var s = internal.GetSingletonObject() + s.SayHi() +}