一个不能全球访问的Singleton [英] A Singleton that is not globally accessible

查看:132
本文介绍了一个不能全球访问的Singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道什么最好的方法是摆脱全局可用的静态getInstance()在单例。我不想从我的程序中的每一个点访问我的Singleton类。

I just wondered what the best way is to get rid of the globally available static getInstance() in a Singleton. I do not want my Singleton classes being accessed from every point in my program.

我想到可能有一个create()public static function创建一个对象并返回它但是不能调用这个方法两次。

I thought about maybe having a create() public static function that creates one object and returns it but one cannot call this method twice.

但是对我来说不是很优雅。比起我将要做一个断言或抛出异常,如果create()第二次调用。

But it's not very elegant for me. Than I would have to make an assertion or throw an exception in case create() gets called a second time.

有没有其他方法,我可以实现我想要的?

Is there any other way I can achieve what I want?

推荐答案

你说第二次创建会破坏整个应用程序。我的回答是:所以不要超过一个。在C ++中,类型系统太弱,无法在编译时轻松确保。我们仍然可以写一个实用程序来在运行时近似它。

You said that "creating one a second time would damage the whole application.". My response is: so don't make more then one. In C++, the type system is too weak to easily ensure this at compile-time. We can still write up a utility to approximate it at run-time, though.

但是,请注意,这并不意味着你应该使用单例。 (你不需要一个全局;不幸的是无人机与全局关联的单实例)。你想要的是这样:

Note, though, that this in no way implies you should use a singleton. (You have zero need for a global; it's unfortunate the drones have associated single-instance with global). What you want is this:

#include <stdexcept>

// inherit from this class (privately) to ensure only
// a single instance of the derived class is created
template <typename D> // CRTP (to give each instantiation its own flag)
class single_instance
{
protected: // protected constructors to ensure this is used as a mixin
    single_instance()
    {
        if (mConstructed)
            throw std::runtime_error("already created");

        mConstructed = true;
    }

    ~single_instance()
    {
        mConstructed = false;
    }

private:
    // private and not defined in order to
    // force the derived class be noncopyable
    single_instance(const single_instance&);
    single_instance& operator=(const single_instance&);

    static bool mConstructed;
};

template <typename T>
bool single_instance<T>::mConstructed = false;

现在,如果类被构造多次,就会出现异常:

Now you get an exception if the class is constructed more than once:

class my_class : private single_instance<my_class>
{
public:
    // usual interface (nonycopyable)
};

int main()
{
    my_class a; // okay
    my_class b; // exception
}

这篇关于一个不能全球访问的Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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