您的位置 首页 golang

Golang设计模式——单例模式

要点:

  1. sync.Once 的应用
  2. 高并发场景下读写锁
package singleton
import "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 singleton
import "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 singleton
import (
  "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

关于作者: 智云科技

热门文章

评论已关闭

5条评论

  1. Three separate 2 well chamber slides were used in this experiment n 6 wells per condition

  2. Diagnostic tests are needed to diagnose heat stroke and assess the extent of vital organ dysfunction, including

  3. Inhibition of migration and invasiveness of highly metastatic cancer cells The diet level soft, pureed, mechanical soft, or regular should be noted

网站地图