Singleton in go

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

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

相关标签:
9条回答
  • 2021-01-30 11:18

    You can do initialization using the once package:

    This will ensure that your init methods only get called once.

    0 讨论(0)
  • 2021-01-30 11:20

    Just put your variables and functions at the package level.

    Also see similar question: How to make a singleton in Python

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题