Skip to content

Commit 3d2d78a

Browse files
committed
Add singleton creational pattern
1 parent d90a201 commit 3d2d78a

File tree

3 files changed

+37
-22
lines changed

3 files changed

+37
-22
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ __Creational Patterns__:
1919
| [Builder](builder/builder.go) | Builds a complex object using simple objects |
2020
| [Factory Method](factory_method.go) | Defers instantiation of an object to a specialized function for creating instances |
2121
| [Object Pool](object_pool/pool.go) | Instantiates and maintains a group of objects instances of the same type |
22-
| [Singleton](singleton/singleton.go) | Restricts instantiation of a class to one object |
22+
| [Singleton](creational/singleton.md) | Restricts instantiation of a type to one object |
2323

2424
__Structural Patterns__:
2525

@@ -29,7 +29,7 @@ __Structural Patterns__:
2929
| [Bridge](bridge.go) | Decouples an interface from its implementation so that the two can vary independently |
3030
| [Composite](composite.go) | Encapsulates and provides access to a number of different objects |
3131
| [Decorator](structural/decorator.md) | Adds behavior to an object, statically or dynamically |
32-
| [Facade](facade.go) | Uses one class as an API to a number of others |
32+
| [Facade](facade.go) | Uses one type as an API to a number of others |
3333
| [Flyweight](flyweight.go) | Reuses existing instances of objects with similar/identical state to minimize resource usage |
3434
| [Model View Controller](mvc.go) | Divides an app into three interconnected parts to separate internal representation from presentation to user |
3535
| [Proxy](proxy.go) | Provides a surrogate for an object to control it's actions |

creational/singleton.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#Singleton Pattern
2+
Singleton creational design pattern restricts the instantiation of a type to a single object.
3+
4+
## Implementation
5+
```go
6+
package singleton
7+
8+
type singleton map[string]string
9+
10+
var once sync.Once
11+
12+
var instance *singleton
13+
14+
func New() *singleton {
15+
once.Do(func() {
16+
instance = make(singleton)
17+
})
18+
19+
return instance
20+
}
21+
```
22+
23+
## Usage
24+
```go
25+
s := singleton.New()
26+
27+
s["this"] = "that"
28+
29+
s2 := singleton.New()
30+
31+
// s2["this"] == "that"
32+
```
33+
34+
## Rules of Thumb
35+
- Singleton pattern represents a global state and most of the time reduces testability.

singleton/singleton.go

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)