Add singleton creational pattern

This commit is contained in:
Tamer Tas
2016-05-14 16:12:50 +03:00
parent d90a201871
commit 3d2d78a8a2
3 changed files with 37 additions and 22 deletions

35
creational/singleton.md Normal file
View File

@@ -0,0 +1,35 @@
#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.