Skip to content

Commit fc6b5df

Browse files
committed
add singleton
1 parent 173ce4e commit fc6b5df

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

03_singleton/singleton.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package singleton
2+
3+
import "sync"
4+
5+
//Singleton 是单例模式类
6+
type Singleton struct{}
7+
8+
var singletonInst *Singleton
9+
var singletonInstLock sync.Mutex
10+
11+
//GetInstance 用于获取单例模式对象
12+
func GetInstance() *Singleton {
13+
if singletonInst == nil {
14+
singletonInstLock.Lock()
15+
if singletonInst == nil {
16+
singletonInst = &Singleton{}
17+
}
18+
}
19+
return singletonInst
20+
}

03_singleton/singleton_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package singleton
2+
3+
import "testing"
4+
5+
func TestSingleton(t *testing.T) {
6+
ins1 := GetInstance()
7+
ins2 := GetInstance()
8+
if ins1 != ins2 {
9+
t.Fatal("instance is not equal")
10+
}
11+
}

0 commit comments

Comments
 (0)