Singleton in go

后端 未结 9 2025
心在旅途
心在旅途 2021-01-30 10:46

How does one implement the Singleton design pattern in the go programming language?

9条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 11:22

    Easy peasy as you can see in the following code:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    type singleton struct {
        count int
        sync.RWMutex
    }
    
    var instance singleton 
    
    func GetInstance() *singleton {
        return &instance 
    }
    
    func (s *singleton) AddOne() {
        s.Lock()
        defer s.Unlock()
        s.count++
    }
    
    func (s *singleton) GetCount() int {
        s.RLock()
        defer s.RUnlock()
        return s.count
    }
    
    func main() {
        obj1 := GetInstance()
        obj1.AddOne()
        fmt.Println(obj1.GetCount())
        obj2 := GetInstance()
        obj2.AddOne()
        fmt.Println(obj2.GetCount())    
        obj3 := GetInstance()
        obj3.AddOne()
        fmt.Println(obj3.GetCount())
    }
    

    Expected result would be:

    1 2 3

    Because you're accessing to the same resource. That's the reason I've added mutex in order to be concurrent proven accessing count attribute from multiple processes. :-)

    Source:

    https://play.golang.org/p/2XnLztX8Gs5

提交回复
热议问题