Skip to content

Commit d382010

Browse files
fgksgfsenghoo
authored andcommitted
update singleton
1 parent 617f418 commit d382010

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

03_singleton/singleton.go

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,27 @@ package singleton
22

33
import "sync"
44

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() {}
715

8-
var singleton *Singleton
9-
var once sync.Once
16+
var (
17+
instance *singleton
18+
once sync.Once
19+
)
1020

1121
//GetInstance 用于获取单例模式对象
12-
func GetInstance() *Singleton {
22+
func GetInstance() Singleton {
1323
once.Do(func() {
14-
singleton = &Singleton{}
24+
instance = &singleton{}
1525
})
1626

17-
return singleton
27+
return instance
1828
}

03_singleton/singleton_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func TestParallelSingleton(t *testing.T) {
1919
start := make(chan struct{})
2020
wg := sync.WaitGroup{}
2121
wg.Add(parCount)
22-
instances := [parCount]*Singleton{}
22+
instances := [parCount]Singleton{}
2323
for i := 0; i < parCount; i++ {
2424
go func(index int) {
2525
//协程阻塞,等待channel被关闭才能继续运行
@@ -37,4 +37,3 @@ func TestParallelSingleton(t *testing.T) {
3737
}
3838
}
3939
}
40-

0 commit comments

Comments
 (0)