单身亡 [英] Singleton in go

查看:134
本文介绍了单身亡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在go编程语言中实现Singleton设计模式?

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

推荐答案

设置是否实现单例模式是一个好主意,这是一个可能的实现:

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;
}

单个 code>实例化是私有的,但 New()是公开的。因此,您不能直接实例化单个而不通过 New(),并跟踪实例的数量私人布尔值实例化。调整单个的定义来尝试。

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.

然而,由于其他几个人都有注意到,这不是线程安全的,除非你只是在<$ c $中初始化你的单身人士C>的init()。一个更好的方法是利用 sync.Once 为你做的努力:

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
}

另请参见hasan j的建议,只是将包 单一化。最后,请考虑别人的建议:单身人士通常是有问题的实施的指标。

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.

这篇关于单身亡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆