0%

go singleton with sync.Once

sync의 Once 를 활용하여 go 싱글톤을 구현합니다.
https://golang.org/pkg/sync/#Once

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package unit

import "sync"

// package level variable
var instance *Component
var once sync.Once

type Component struct {
count int
}

func GetInstance() *Component {
once.Do(func() {
instance = &Component{count: 0}
})
return instance
}

func (s *Component) add() {
s.count++
}

func (s *Component) getCount() int {
return s.count
}

test code

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

import (
"fmt"
"testing"
)

func TestGetInstance(t *testing.T) {
GetInstance().add()
fmt.Println(GetInstance().getCount())

GetInstance().add()
fmt.Println(GetInstance().getCount())

GetInstance().add()
fmt.Println(GetInstance().getCount())
}

실행 결과

1
2
3
4
5
6
D:\repository\singleton_test\test>go test
1
2
3
PASS
ok _/D_/repository/singleton_test/test 0.171s