Golang patterns

From wikinotes
Revision as of 16:24, 22 July 2022 by Will (talk | contribs) (Created page with "Some design pattern implementations in go = Singleton = <blockquote> <syntaxhighlight lang="go"> // src: https://medium.com/golang-issue/how-singleton-pattern-works-with-golang-2fdd61cd5a7f var once sync.Once // type global type singleton map[string]string var ( instance singleton ) func NewClass() singleton { once.Do(func() { // <-- atomic, does not allow repeating instance = make(singleton) // <-- thread safe }) return instance } </syntaxhighlight> </blo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Some design pattern implementations in go

Singleton

// src: https://medium.com/golang-issue/how-singleton-pattern-works-with-golang-2fdd61cd5a7f

var once sync.Once

// type global
type singleton map[string]string

var (
	instance singleton
)

func NewClass() singleton {

	once.Do(func() { // <-- atomic, does not allow repeating

		instance = make(singleton) // <-- thread safe

	})

	return instance
}