mirror of
https://github.com/tmrts/go-patterns.git
synced 2024-11-28 16:06:07 +03:00
36 lines
551 B
Markdown
36 lines
551 B
Markdown
|
#Singleton Pattern
|
||
|
Singleton creational design pattern restricts the instantiation of a type to a single object.
|
||
|
|
||
|
## Implementation
|
||
|
```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
|
||
|
```go
|
||
|
s := singleton.New()
|
||
|
|
||
|
s["this"] = "that"
|
||
|
|
||
|
s2 := singleton.New()
|
||
|
|
||
|
// s2["this"] == "that"
|
||
|
```
|
||
|
|
||
|
## Rules of Thumb
|
||
|
- Singleton pattern represents a global state and most of the time reduces testability.
|