File tree Expand file tree Collapse file tree 2 files changed +18
-9
lines changed Expand file tree Collapse file tree 2 files changed +18
-9
lines changed Original file line number Diff line number Diff line change @@ -2,17 +2,27 @@ package singleton
2
2
3
3
import "sync"
4
4
5
- //Singleton 是单例模式类
6
- type Singleton struct {}
5
+ // Singleton 是单例模式接口,导出的
6
+ // 通过该接口可以避免 GetInstance 返回一个包私有类型的指针
7
+ type Singleton interface {
8
+ foo ()
9
+ }
10
+
11
+ // singleton 是单例模式类,包私有的
12
+ type singleton struct {}
13
+
14
+ func (s singleton ) foo () {}
7
15
8
- var singleton * Singleton
9
- var once sync.Once
16
+ var (
17
+ instance * singleton
18
+ once sync.Once
19
+ )
10
20
11
21
//GetInstance 用于获取单例模式对象
12
- func GetInstance () * Singleton {
22
+ func GetInstance () Singleton {
13
23
once .Do (func () {
14
- singleton = & Singleton {}
24
+ instance = & singleton {}
15
25
})
16
26
17
- return singleton
27
+ return instance
18
28
}
Original file line number Diff line number Diff line change @@ -19,7 +19,7 @@ func TestParallelSingleton(t *testing.T) {
19
19
start := make (chan struct {})
20
20
wg := sync.WaitGroup {}
21
21
wg .Add (parCount )
22
- instances := [parCount ]* Singleton {}
22
+ instances := [parCount ]Singleton {}
23
23
for i := 0 ; i < parCount ; i ++ {
24
24
go func (index int ) {
25
25
//协程阻塞,等待channel被关闭才能继续运行
@@ -37,4 +37,3 @@ func TestParallelSingleton(t *testing.T) {
37
37
}
38
38
}
39
39
}
40
-
You can’t perform that action at this time.
0 commit comments