可派类的单例模式

时间:2016-12-05 17:34:03

标签: c++ design-patterns singleton

在正常的单身人士模式中,单身人士课程实际上是“密封的”#34; (不能派生):

class A
{
private:
    static A m_instance; // instance of this class, not a subclass

    // private ctor/dtor, so class can't be derived
    A();
    ~A();

public:
    static A& GetInstance() { return m_instance; }

    ...
};

你如何编写一个意图派生的类,但其派生类只应实例化一次?

1 个答案:

答案 0 :(得分:4)

  

你如何编写一个意图派生的类,但其派生类只应实例化一次?

您可以使用CRTP来实现:

template<typename Derived>
class A
{
protected: // Allow to call the constructor and destructor from a derived class
    A(); 
    ~A();

public:
    static T& GetInstance() { 
        static T theInstance; // Better way than using a static member variable
        return theInstance;
    }

    ...
};

并使用

class B : public A<B> {
    // Specific stuff for derived class
};

请注意,如果基类提供了一些基于派生类提供的接口的常见实现(除GetInstance()函数之外),这种方式最有意义。

每当需要调用基类中的派生类时,您可以安全地使用static_cast<Derived*>(this)来访问它(不需要virtual或纯virtual函数):

 template<typename Derived> 
 void A<Derived>::doSomething {
      // Execute the functions from Derived that actually implement the 
      // warranted behavior.
      static_cast<Derived*>(this)->foo();
      static_cast<Derived*>(this)->bar();
 }