1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-24 14:06:06 +03:00

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

View File

@ -19,7 +19,7 @@ __Creational Patterns__:
| [Builder](builder/builder.go) | Builds a complex object using simple objects |
| [Factory Method](factory_method.go) | Defers instantiation of an object to a specialized function for creating instances |
| [Object Pool](object_pool/pool.go) | Instantiates and maintains a group of objects instances of the same type |
| [Singleton](singleton/singleton.go) | Restricts instantiation of a class to one object |
| [Singleton](creational/singleton.md) | Restricts instantiation of a type to one object |
__Structural Patterns__:
@ -29,7 +29,7 @@ __Structural Patterns__:
| [Bridge](bridge.go) | Decouples an interface from its implementation so that the two can vary independently |
| [Composite](composite.go) | Encapsulates and provides access to a number of different objects |
| [Decorator](structural/decorator.md) | Adds behavior to an object, statically or dynamically |
| [Facade](facade.go) | Uses one class as an API to a number of others |
| [Facade](facade.go) | Uses one type as an API to a number of others |
| [Flyweight](flyweight.go) | Reuses existing instances of objects with similar/identical state to minimize resource usage |
| [Model View Controller](mvc.go) | Divides an app into three interconnected parts to separate internal representation from presentation to user |
| [Proxy](proxy.go) | Provides a surrogate for an object to control it's actions |

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.

View File

@ -1,20 +0,0 @@
package singleton
import (
"sync"
)
type Object struct {
}
var once sync.Once
var instance *Object
func GetInstance() *Object {
// Creates a singleton instance once.
once.Do(func() {
instance = &singleton{}
})
return instance
}