[设计模式 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
}

单元测试

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")
		}
	}
}

相关推荐

  1. [设计模式 Go实现] 创建模式

    2024-01-01 08:38:04       37 阅读
  2. GO设计模式——4、模式创建

    2024-01-01 08:38:04       41 阅读
  3. 设计模式 创建模式

    2024-01-01 08:38:04       35 阅读
  4. 设计模式-模式创建

    2024-01-01 08:38:04       10 阅读
  5. 设计模式模式创建)⭐⭐⭐

    2024-01-01 08:38:04       8 阅读
  6. 创建--模式

    2024-01-01 08:38:04       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 08:38:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 08:38:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 08:38:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 08:38:04       20 阅读

热门阅读

  1. Anaconda下调用ArcGIS的arcpy工具包

    2024-01-01 08:38:04       45 阅读
  2. 数据挖掘 模糊聚类

    2024-01-01 08:38:04       45 阅读
  3. LeetCode75| 单调栈

    2024-01-01 08:38:04       42 阅读
  4. 一篇文章认识微服务的优缺点和微服务技术栈

    2024-01-01 08:38:04       37 阅读
  5. 九台虚拟机网站流量分析项目启动步骤

    2024-01-01 08:38:04       41 阅读