Inherit Singleton

Inherit Singleton

本文关键字:Singleton Inherit      更新时间:2023-10-16

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

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

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

在Coliru上直播

singleton有一个静态getInstance()方法,该方法在第一次调用时创建该类的单个实例,因此静态绑定到正在实例化的singleton类的类型。我看不出拥有辛格尔顿层次结构的直接效用。但是,如果您坚持要有一个方法,您可以考虑将getInstance方法设置为virtual,并在扩展父Singleton的类中重写它。

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

当然,一个健壮的实现将存储并返回智能指针。