【问题标题】:Singleton pattern for derivable class可派生类的单例模式
【发布时间】:2016-12-06 02:12:54
【问题描述】:

在正常的单例模式中,单例类被有效地“密封”(不能派生):

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

    ...
};

您将如何编写一个派生类,但其派生类只应实例化一次?

【问题讨论】:

标签: c++ design-patterns singleton


【解决方案1】:

您将如何编写一个派生类,但其派生类只应实例化一次?

您可以使用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&lt;Derived*&gt;(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();
 }

【讨论】:

  • static T theInstance; 客观上“更好”吗?肯定都编译成同一个东西吗?
  • @Michael 它不会编译成同样的东西,这就是它更好的原因。
  • @Michael 查找 Scott Meyer 的 Singleton 以及为什么这是先进和更好的方法(例如线程安全)。
猜你喜欢
  • 2019-09-24
  • 2021-11-16
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
相关资源
最近更新 更多