01-Go设计模式-单例模式

Go设计模式 - 单例模式

实现代码

/*
单例模式

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

package _3_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
}

测试代码

package _3_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)
	instance := [parCount]Singleton{}
	for i := 0; i < parCount; i++ {
		go func(index int) {
			//协程阻塞,等待channel被关闭才能继续运行
			<-start
			instance[index] = GetInstance()
			wg.Done()
		}(i)
	}

	//关闭channel,所有协程同时开始运行,实现并行(parallel)
	close(start)
	wg.Wait()

	for i := 1; i < parCount; i++ {
		if instance[i] != instance[i-1] {
			t.Fatal("instance is not equal")
		}
	}
}

posted @   李成果  阅读(39)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示