Skip to content

Commit 6d63c20

Browse files
committed
add once singletion demo
1 parent 1584dd6 commit 6d63c20

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/creational/03_singleton/singleton.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,43 @@ import (
88
type Singleton struct {
99
}
1010

11+
var (
12+
singleton *Singleton
13+
singlock sync.Mutex
14+
)
15+
16+
// DoSomething just for test
1117
func (s *Singleton) DoSomething() {
12-
fmt.Println("Tish is a Singleton")
18+
fmt.Println("this is a Singleton")
1319
}
1420

15-
var singleton *Singleton
16-
var singlock sync.Mutex
17-
18-
//
21+
// Singleton return Singleton
1922
func GetSingleton() *Singleton {
2023
singlock.Lock()
2124
if singleton == nil {
2225
singleton = &Singleton{}
2326
}
2427
singlock.Unlock()
2528
return singleton
29+
}
2630

31+
var (
32+
singleton2 *Singleton
33+
done sync.Once
34+
)
35+
36+
// Singleton return Singleton
37+
func GetSingleton2() *Singleton {
38+
done.Do(func() {
39+
singleton2 = &Singleton{}
40+
})
41+
return singleton2
2742
}
2843

2944
func main() {
3045
singlet := GetSingleton()
3146
singlet.DoSomething()
47+
48+
singlet2 := GetSingleton2()
49+
singlet2.DoSomething()
3250
}

0 commit comments

Comments
 (0)