mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-25 06:16:03 +03:00
added singleton pattern
This commit is contained in:
parent
14eee3e9ee
commit
2b797ef4dc
12
creational/main.go
Normal file
12
creational/main.go
Normal 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())
|
||||||
|
}
|
23
creational/singleton/singleton.go
Normal file
23
creational/singleton/singleton.go
Normal 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
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user