From d382010cbcf634cc6a4724895b182c6d3b837607 Mon Sep 17 00:00:00 2001 From: Hoshea Date: Sat, 1 May 2021 16:40:11 +0800 Subject: [PATCH] update singleton --- 03_singleton/singleton.go | 24 +++++++++++++++++------- 03_singleton/singleton_test.go | 3 +-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/03_singleton/singleton.go b/03_singleton/singleton.go index c99a380..9f269ab 100644 --- a/03_singleton/singleton.go +++ b/03_singleton/singleton.go @@ -2,17 +2,27 @@ package singleton import "sync" -//Singleton 是单例模式类 -type Singleton struct{} +// Singleton 是单例模式接口,导出的 +// 通过该接口可以避免 GetInstance 返回一个包私有类型的指针 +type Singleton interface { + foo() +} + +// singleton 是单例模式类,包私有的 +type singleton struct{} + +func (s singleton) foo() {} -var singleton *Singleton -var once sync.Once +var ( + instance *singleton + once sync.Once +) //GetInstance 用于获取单例模式对象 -func GetInstance() *Singleton { +func GetInstance() Singleton { once.Do(func() { - singleton = &Singleton{} + instance = &singleton{} }) - return singleton + return instance } diff --git a/03_singleton/singleton_test.go b/03_singleton/singleton_test.go index f143b33..edf9908 100644 --- a/03_singleton/singleton_test.go +++ b/03_singleton/singleton_test.go @@ -19,7 +19,7 @@ func TestParallelSingleton(t *testing.T) { start := make(chan struct{}) wg := sync.WaitGroup{} wg.Add(parCount) - instances := [parCount]*Singleton{} + instances := [parCount]Singleton{} for i := 0; i < parCount; i++ { go func(index int) { //协程阻塞,等待channel被关闭才能继续运行 @@ -37,4 +37,3 @@ func TestParallelSingleton(t *testing.T) { } } } -