1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-25 06:26:06 +03:00
go-patterns/creational/singleton.md

41 lines
584 B
Markdown
Raw Normal View History

# Singleton Pattern
2016-05-14 16:12:50 +03:00
Singleton creational design pattern restricts the instantiation of a type to a single object.
## Implementation
2016-05-14 16:12:50 +03:00
```go
package singleton
type singleton map[string]string
var once sync.Once
var instance *singleton
func New() *singleton {
once.Do(func() {
instance = make(singleton)
})
return instance
}
```
## Usage
2016-05-14 16:12:50 +03:00
```go
s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])
// This is that
2016-05-14 16:12:50 +03:00
```
## Rules of Thumb
2016-05-14 16:12:50 +03:00
- Singleton pattern represents a global state and most of the time reduces testability.