要点:
-
sync.Once 的应用
-
高并发场景下读写锁
package singletonimport "sync"var ( p *Pet once sync.Once)func init(){ once.Do( func() { p = &Pet{} })}func GetInstance() *Pet{ return p}type Pet struct { Name string Age int m sync.Mutex}func (p *Pet)GetName()string{ return p.Name}func (p *Pet) GetAge() int{ return p.Age}func(p *Pet) SetName(name string) { p.m.Lock() defer p.m.Unlock() p.Name = name}func(p *Pet) IncAge() { p.m.Lock() defer p.m.Unlock() p.Age++}
测试用例
package singletonimport "testing"func TestGetInstance(t *testing.T) { p := GetInstance() p.SetName("tommy") p.IncAge() p.GetName() p.GetAge()}
测试并发场景
func IncAgeTest1(){ p = GetInstance() p.IncAge()}func IncAgeTest2(){ p = GetInstance() p.IncAge()}
package singletonimport ( "fmt" "sync" "testing")func TestGetInstance(t *testing.T) { wg := sync.WaitGroup{} wg.Add(200) for i:=0;i<100;i++{ go func() { defer wg.Done() IncAgeTest1() }() go func() { defer wg.Done() IncAgeTest2() }() } wg.Wait() p := GetInstance() fmt.Println(p.Age)}
// output=== RUN TestGetInstance200
文章来源:智云一二三科技
文章标题:Golang设计模式——单例模式
文章地址:https://www.zhihuclub.com/71.shtml