File tree Expand file tree Collapse file tree 1 file changed +23
-5
lines changed
src/creational/03_singleton Expand file tree Collapse file tree 1 file changed +23
-5
lines changed Original file line number Diff line number Diff line change @@ -8,25 +8,43 @@ import (
8
8
type Singleton struct {
9
9
}
10
10
11
+ var (
12
+ singleton * Singleton
13
+ singlock sync.Mutex
14
+ )
15
+
16
+ // DoSomething just for test
11
17
func (s * Singleton ) DoSomething () {
12
- fmt .Println ("Tish is a Singleton" )
18
+ fmt .Println ("this is a Singleton" )
13
19
}
14
20
15
- var singleton * Singleton
16
- var singlock sync.Mutex
17
-
18
- //
21
+ // Singleton return Singleton
19
22
func GetSingleton () * Singleton {
20
23
singlock .Lock ()
21
24
if singleton == nil {
22
25
singleton = & Singleton {}
23
26
}
24
27
singlock .Unlock ()
25
28
return singleton
29
+ }
26
30
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
27
42
}
28
43
29
44
func main () {
30
45
singlet := GetSingleton ()
31
46
singlet .DoSomething ()
47
+
48
+ singlet2 := GetSingleton2 ()
49
+ singlet2 .DoSomething ()
32
50
}
You can’t perform that action at this time.
0 commit comments