2016-12-05 57 views
3

在正常的單模式,單例類被有效地「密封」(不能得出):Singleton模式衍生類

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

    ... 
}; 

你會怎麼寫,就是要派生的類,但其派生類應該只實例化一次?

+0

相關:HTTP://計算器。 com/questions/5739678/c-templates-and-the-singleton-pattern –

回答

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(); 
} 
+0

是「static T theInstance;'客觀上」更好「?當然,兩者都是一樣的東西? – Michael

+1

@Michael它不會編譯成相同的東西,這就是爲什麼它更好。 –

+2

@Michael查找_Scott Meyer的Singleton_以及爲什麼這是先進和更好的方法(例如線程安全)。 –