From 2b797ef4dc4c0311df3f1a3095ea77f00ab96f58 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Thu, 9 Nov 2017 20:22:11 +1000 Subject: [PATCH] added singleton pattern --- creational/main.go | 12 ++++++++++++ creational/singleton/singleton.go | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 creational/main.go create mode 100644 creational/singleton/singleton.go 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 +}