Singleton in go

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

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

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 11:02

    Setting aside the argument of whether or not implementing the singleton pattern is a good idea, here's a possible implementation:

    package singleton
    
    type single struct {
            O interface{};
    }
    
    var instantiated *single = nil
    
    func New() *single {
            if instantiated == nil {
                    instantiated = new(single);
            }
            return instantiated;
    }
    

    single and instantiated are private, but New() is public. Thus, you can't directly instantiate single without going through New(), and it tracks the number of instantiations with the private boolean instantiated. Adjust the definition of single to taste.

    However, as several others have noted, this is not thread-safe, unless you're only initializing your singleton in init(). A better approach would be to leverage sync.Once to do the hard work for you:

    package singleton
    
    import "sync"
    
    type single struct {
            O interface{};
    }
    
    var instantiated *single
    var once sync.Once
    
    func New() *single {
            once.Do(func() {
                    instantiated = &single{}
            })
            return instantiated
    }
    

    See also, hasan j's suggestion of just thinking of a package as a singleton. And finally, do consider what others are suggesting: that singletons are often an indicator of a problematic implementation.

提交回复
热议问题