Skip to content

Commit

Permalink
Add singleton creational pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
tmrts committed May 14, 2016
1 parent d90a201 commit 3d2d78a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 22 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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__:

Expand All @@ -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 |
Expand Down
35 changes: 35 additions & 0 deletions creational/singleton.md
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 0 additions & 20 deletions singleton/singleton.go

This file was deleted.

0 comments on commit 3d2d78a

Please sign in to comment.