forked from betty200744/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.go
43 lines (38 loc) · 857 Bytes
/
singleton.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package singleton
import (
"fmt"
"sync"
)
/*
DB instance – we only want to create only one instance of DB object and that instance will be used throughout the application.
Logger instance – again only one instance of the logger should be created and it should be used throughout the application.
*/
var (
lock = &sync.Mutex{}
once = &sync.Once{}
single *Single
)
type Single struct {
}
func GetInstance1() *Single {
if single == nil {
lock.Lock()
defer lock.Unlock()
single = &Single{}
fmt.Println("Creating Single Instance Now")
} else {
fmt.Println("Single Instance already created")
}
return single
}
func GetInstance2() *Single {
if single == nil {
once.Do(func() {
single = &Single{}
})
fmt.Println("Creating Single Instance Now")
} else {
fmt.Println("Single Instance already created")
}
return single
}