2016-09-06 19:26:44 +03:00
|
|
|
# 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-09-06 19:26:44 +03:00
|
|
|
|
2016-05-14 16:12:50 +03:00
|
|
|
```go
|
|
|
|
package singleton
|
|
|
|
|
|
|
|
type singleton map[string]string
|
|
|
|
|
2017-01-13 09:34:48 +03:00
|
|
|
var (
|
|
|
|
once sync.Once
|
2016-05-14 16:12:50 +03:00
|
|
|
|
2017-01-13 09:34:48 +03:00
|
|
|
instance singleton
|
|
|
|
)
|
2016-05-14 16:12:50 +03:00
|
|
|
|
2016-10-19 17:35:51 +03:00
|
|
|
func New() singleton {
|
2016-05-14 16:12:50 +03:00
|
|
|
once.Do(func() {
|
|
|
|
instance = make(singleton)
|
|
|
|
})
|
|
|
|
|
|
|
|
return instance
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Usage
|
2016-09-06 19:26:44 +03:00
|
|
|
|
2016-05-14 16:12:50 +03:00
|
|
|
```go
|
|
|
|
s := singleton.New()
|
|
|
|
|
|
|
|
s["this"] = "that"
|
|
|
|
|
|
|
|
s2 := singleton.New()
|
|
|
|
|
2016-09-06 19:26:44 +03:00
|
|
|
fmt.Println("This is ", s2["this"])
|
|
|
|
// This is that
|
2016-05-14 16:12:50 +03:00
|
|
|
```
|
|
|
|
|
|
|
|
## Rules of Thumb
|
2016-09-06 19:26:44 +03:00
|
|
|
|
2016-05-14 16:12:50 +03:00
|
|
|
- Singleton pattern represents a global state and most of the time reduces testability.
|