mirror of
https://github.com/Estom/notes.git
synced 2026-02-08 13:05:57 +08:00
go知识重新整理
This commit is contained in:
24
Go/DesignPattern/single/single.go
Normal file
24
Go/DesignPattern/single/single.go
Normal file
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* @Author:zhoutao
|
||||
* @Date:2020/12/12 下午4:14
|
||||
* @Desc:
|
||||
*/
|
||||
|
||||
package single
|
||||
|
||||
import "sync"
|
||||
|
||||
//单例模式:使用懒惰模式的单例模式,使用双重检查加锁保证线程安全
|
||||
|
||||
type Singleton struct {
|
||||
}
|
||||
|
||||
var singelton *Singleton
|
||||
var once sync.Once
|
||||
|
||||
func GetInstance() *Singleton {
|
||||
once.Do(func() {
|
||||
singelton = &Singleton{}
|
||||
})
|
||||
return singelton
|
||||
}
|
||||
45
Go/DesignPattern/single/single_test.go
Normal file
45
Go/DesignPattern/single/single_test.go
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @Author:zhoutao
|
||||
* @Date:2020/12/13 上午10:48
|
||||
* @Desc:
|
||||
*/
|
||||
|
||||
package single
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const parCount = 100
|
||||
|
||||
func TestSingleton(t *testing.T) {
|
||||
ins1 := GetInstance()
|
||||
ins2 := GetInstance()
|
||||
if ins1 != ins2 {
|
||||
t.Fatal("instance is not equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParalleSingleton(t *testing.T) {
|
||||
start := make(chan struct{})
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(parCount)
|
||||
instances := [parCount]*Singleton{}
|
||||
for i := 0; i < parCount; i++ {
|
||||
go func(index int) {
|
||||
//等待channel的关闭信号
|
||||
<-start
|
||||
instances[index] = GetInstance()
|
||||
wg.Done()
|
||||
}(i)
|
||||
}
|
||||
//关闭channel,发送关闭信号
|
||||
close(start)
|
||||
wg.Wait()
|
||||
for i := 1; i < parCount; i++ {
|
||||
if instances[i] != instances[i-1] {
|
||||
t.Fatal("instance is not equal")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user