[设计模式 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")
		}
	}
}
相关推荐
平头哥AI11 小时前
Day 22 _ 包装错误别丢链_%w、errors.Is 与 errors.As
android·服务器·学习·golang·go
golang学习记15 小时前
Go 1.27新特性: json/v2使用有趣指南
开发语言·golang·json
王码码203516 小时前
Go语言CGO:Go与C交互
后端·golang·go·接口
PC2005-cloud17 小时前
DSH 白嫖指南:接入 Command Code Go、WorkBuddy 与 Trae 的免费额度
开发语言·后端·golang
名字还没想好☜19 小时前
Docker 镜像瘦身进阶:用 distroless/scratch 把 Go 服务打到 10MB,以及没 shell 怎么调试
运维·docker·容器·golang·kubernetes
lvshuocool19 小时前
golang 多版本管理工具 -- g
开发语言·后端·golang
善良勤劳勇敢而又聪明的老杨1 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程
海盗12341 天前
DSH 接入 OpenCode Go 报 400 MissingSessionID:从 LLM 语义层退到 fetch 传输层的完整排障
开发语言·后端·golang
geovindu1 天前
java: Strategy Pattern
java·开发语言·后端·设计模式·策略模式·行为模式
web守墓人1 天前
【goed/ui】go开发windows原生应用之Helloworld篇
windows·ui·golang