Singleton in go

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

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

9条回答
  •  死守一世寂寞
    2021-01-30 11:00

    I think that in a concurrent world we need to be a bit more aware that these lines are not executed atomically:

    if instantiated == nil {
        instantiated = new(single);
    }
    

    I would follow the suggestion of @marketer and use the package "sync"

    import "sync"
    
    type MySingleton struct {
    
    }
    
    var _init_ctx sync.Once 
    var _instance *MySingleton
    
    func New() * MySingleton {
         _init_ctx.Do( func () { _instance = new(MySingleton) }  )
         return _instance 
    }
    

提交回复
热议问题