Skip to content

Commit b55d7cf

Browse files
xpzouyingsenghoo
authored andcommitted
update singleton
1. 修改mutex为sync.Once 2. 命名更加golang语言化
1 parent cf32d44 commit b55d7cf

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

03_singleton/singleton.go

+7-9
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,14 @@ import "sync"
55
//Singleton 是单例模式类
66
type Singleton struct{}
77

8-
var singletonInst *Singleton
9-
var singletonInstLock sync.Mutex
8+
var singleton *Singleton
9+
var once sync.Once
1010

1111
//GetInstance 用于获取单例模式对象
1212
func GetInstance() *Singleton {
13-
if singletonInst == nil {
14-
singletonInstLock.Lock()
15-
if singletonInst == nil {
16-
singletonInst = &Singleton{}
17-
}
18-
}
19-
return singletonInst
13+
once.Do(func() {
14+
singleton = &Singleton{}
15+
})
16+
17+
return singleton
2018
}

0 commit comments

Comments
 (0)