added singleton pattern

This commit is contained in:
Jian Han 2017-11-09 20:22:11 +10:00
parent 14eee3e9ee
commit 2b797ef4dc
2 changed files with 35 additions and 0 deletions

12
creational/main.go Normal file
View File

@ -0,0 +1,12 @@
package main
import (
"fmt"
"github.com/jianhan/go-patterns/creational/singleton"
)
func main() {
instance := singleton.GetInstance()
fmt.Println(instance.AddOne())
}

View File

@ -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
}