diff --git a/creational/main.go b/creational/main.go new file mode 100644 index 0000000..e87e110 --- /dev/null +++ b/creational/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + + "github.com/jianhan/go-patterns/creational/singleton" +) + +func main() { + instance := singleton.GetInstance() + fmt.Println(instance.AddOne()) +} diff --git a/creational/singleton/singleton.go b/creational/singleton/singleton.go new file mode 100644 index 0000000..96afe26 --- /dev/null +++ b/creational/singleton/singleton.go @@ -0,0 +1,23 @@ +package singleton + +type Singleton interface { + AddOne() int +} + +type singleton struct { + count int +} + +func (s *singleton) AddOne() int { + s.count++ + return s.count +} + +var instance *singleton + +func GetInstance() Singleton { + if instance == nil { + instance = new(singleton) + } + return instance +}