Skip to content

Commit

Permalink
update singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
fgksgf authored and senghoo committed May 12, 2021
1 parent 617f418 commit d382010
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
24 changes: 17 additions & 7 deletions 03_singleton/singleton.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,27 @@ package singleton

import "sync"

//Singleton 是单例模式类
type Singleton struct{}
// Singleton 是单例模式接口,导出的
// 通过该接口可以避免 GetInstance 返回一个包私有类型的指针
type Singleton interface {
foo()
}

// singleton 是单例模式类,包私有的
type singleton struct{}

func (s singleton) foo() {}

var singleton *Singleton
var once sync.Once
var (
instance *singleton
once sync.Once
)

//GetInstance 用于获取单例模式对象
func GetInstance() *Singleton {
func GetInstance() Singleton {
once.Do(func() {
singleton = &Singleton{}
instance = &singleton{}
})

return singleton
return instance
}
3 changes: 1 addition & 2 deletions 03_singleton/singleton_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestParallelSingleton(t *testing.T) {
start := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(parCount)
instances := [parCount]*Singleton{}
instances := [parCount]Singleton{}
for i := 0; i < parCount; i++ {
go func(index int) {
//协程阻塞,等待channel被关闭才能继续运行
Expand All @@ -37,4 +37,3 @@ func TestParallelSingleton(t *testing.T) {
}
}
}

0 comments on commit d382010

Please sign in to comment.