diff --git a/factory/README.md b/factory/README.md new file mode 100644 index 0000000..f3bbaa0 --- /dev/null +++ b/factory/README.md @@ -0,0 +1 @@ +《大话设计模式》-程杰-2007-1.10 简单工厂模式 \ No newline at end of file diff --git a/singleton/README.md b/singleton/README.md new file mode 100644 index 0000000..ae9e31e --- /dev/null +++ b/singleton/README.md @@ -0,0 +1 @@ +https://lailin.xyz/post/singleton.html \ No newline at end of file diff --git a/singleton/hunger.go b/singleton/hunger.go new file mode 100644 index 0000000..aa18787 --- /dev/null +++ b/singleton/hunger.go @@ -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 +} diff --git a/singleton/hunger_test.go b/singleton/hunger_test.go new file mode 100644 index 0000000..cf908ff --- /dev/null +++ b/singleton/hunger_test.go @@ -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") + } + } + }) +} diff --git a/singleton/lazy.go b/singleton/lazy.go new file mode 100644 index 0000000..c12a851 --- /dev/null +++ b/singleton/lazy.go @@ -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 +} diff --git a/singleton/lazy_test.go b/singleton/lazy_test.go new file mode 100644 index 0000000..b54db8a --- /dev/null +++ b/singleton/lazy_test.go @@ -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") + } + } + }) +}