Design Patterns | Singleton

Creational pattern - Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cards

import (
"sync"
)

type holder map[string]string

var storeObject holder
var once sync.Once

func New() holder {
once.Do(func() {
storeObject = make(holder)
})
return storeObject
}

Here we define package cards, that encapsulates relationship between card number and and owner of a card. It’s concurency free function func New() code, that creates object only if it’s not initialized before.

Below you can find the basic usage of this pattern:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"

"cards"
)

func main() {
store := cards.New()
store["1111-2222-3333-4444"] = "John Doe"
store2 := cards.New()
fmt.Println(store2["1111-2222-3333-4444"])
}

Sample output of program shows that there are no another instance was created.