继承单例模式

6

快速问题。有没有办法继承单例,以使子类成为单例?我已经搜索过了,但我找到的每个单例都是按类实现的,而不是以通用的方式实现的。

2个回答

17

是的,有一种通用的方法。您可以通过CRTP实现单例,例如:

template<typename T>
class Singleton
{
protected:
    Singleton() noexcept = default;

    Singleton(const Singleton&) = delete;

    Singleton& operator=(const Singleton&) = delete;

    virtual ~Singleton() = default; // to silence base class Singleton<T> has a
    // non-virtual destructor [-Weffc++]

public:
    static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
    {
        // Guaranteed to be destroyed.
        // Instantiated on first use.
        // Thread safe in C++11
        static T instance{};

        return instance;
    }
};

然后从中派生出一个单例,使您的子对象成为单例:
class MySingleton: public Singleton<MySingleton>
{
    // needs to be friend in order to 
    // access the private constructor/destructor
    friend class Singleton<MySingleton>; 
public:
    // Declare all public members here
private:
    MySingleton()
    {
        // Implement the constructor here
    }
    ~MySingleton()
    {
        // Implement the destructor here
    }
};

Live on Coliru


0
一个单例模式有一个静态的getInstance()方法,第一次调用时创建类的唯一实例,因此在实例化单例类的类型上是静态绑定的。我不认为拥有一个单例层次结构会立即有用。但如果你坚持要有一个,你可以考虑将getInstance方法设为virtual并在扩展父单例的类中重写它。
class Singleton {
    public virtual Singleton * getInstance() const
    {
        // instantiate Singleton if necessary
        // return pointer to instance
    }
    ...
};

class MySingleton : public Singleton {
    // overrides Singelton's getInstance
    public virtual MySingleton * getInstance() const
    {
        // instantiate MySingleton if necessary
        // return pointer to instance
    }
};

当然,一个强大的实现会存储并返回智能指针。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接