feat: add singleton

main
ZGGSONG 2 years ago
parent 4037ea75d0
commit 7d29259efb

@ -0,0 +1 @@
《大话设计模式》-程杰-2007-1.10 简单工厂模式

@ -0,0 +1 @@
https://lailin.xyz/post/singleton.html

@ -0,0 +1,17 @@
package singleton
type Singleton struct{}
var singleton *Singleton
func init() {
singleton = &Singleton{}
}
// GetHungerInstance
//
// @Description: 饿汉式获取实例
// @return *Singleton
func GetHungerInstance() *Singleton {
return singleton
}

@ -0,0 +1,25 @@
package singleton
import (
"testing"
)
func TestHunger(t *testing.T) {
s1 := GetHungerInstance()
s2 := GetHungerInstance()
if s1 == s2 {
t.Log("success")
} else {
t.Fatal("failure")
}
}
func BenchmarkHunger(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if GetHungerInstance() != GetHungerInstance() {
b.Errorf("test fail")
}
}
})
}

@ -0,0 +1,21 @@
package singleton
import "sync"
var (
lazySingleton *Singleton
once = &sync.Once{}
)
// GetLazyInstance
//
// @Description: 懒汉式
// @return *Singleton
func GetLazyInstance() *Singleton {
if lazySingleton == nil {
once.Do(func() {
lazySingleton = &Singleton{}
})
}
return lazySingleton
}

@ -0,0 +1,21 @@
package singleton
import "testing"
func TestGetLazyInstance(t *testing.T) {
if GetLazyInstance() != GetLazyInstance() {
t.Fatal("lazy instance failed")
} else {
t.Log("lazy instance succeeded")
}
}
func BenchmarkGetLazyInstance(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if GetLazyInstance() != GetLazyInstance() {
b.Errorf("test fail")
}
}
})
}
Loading…
Cancel
Save