[设计模式 Go实现] 创建型~单例模式

使用懒惰模式的单例模式,使用双重检查加锁保证线程安全

代码实现

go 复制代码
package singleton

import "sync"

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

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

func (s singleton) foo() {}

var (
	instance *singleton
	once     sync.Once
)

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

	return instance
}

单元测试

go 复制代码
package singleton

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 TestParallelSingleton(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,所有协程同时开始运行,实现并行(parallel)
	close(start)
	wg.Wait()
	for i := 1; i < parCount; i++ {
		if instances[i] != instances[i-1] {
			t.Fatal("instance is not equal")
		}
	}
}
相关推荐
灯澜忆梦6 小时前
GO_并发编程---定时器
开发语言·后端·golang
张小姐的猫15 小时前
【Linux】网络编程 —— HTTP协议(上)
linux·运维·服务器·网络·http·单例模式·策略模式
qq_4523962315 小时前
第二篇:《Go 开发环境搭建:SDK、IDE、Module 与 Hello World》
开发语言·ide·golang
杨充18 小时前
10.可测试性实战设计
设计模式·开源·代码规范
杨充18 小时前
9.重构十二式的实战
设计模式·开源·代码规范
杨充18 小时前
6.设计原则的全景图
设计模式·开源·全栈
杨充18 小时前
2.面向对象的特性
设计模式
杨充18 小时前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充18 小时前
8.反模式与坏味道
设计模式·开源·代码规范
杨充18 小时前
3.接口vs抽象类比较
设计模式