2012-03-31 83 views
2

OO設計問題。每個層次的單個單例繼承

我想繼承singleton功能到不同的層次結構中。這意味着他們需要爲每個層次結構擁有自己的單例實例。

這裏是什麼,我試圖做一個簡單的例子:

class CharacterBob : public CCSprite, public BatchNodeSingleton { 
... 
} 

class CharacterJim : public CCSprite, public BatchNodeSingleton { 
... 
} 


class BatchNodeSingleton { 
public: 
    BatchNodeSingleton(void); 
    ~BatchNodeSingleton(void); 

    CCSpriteBatchNode* GetSingletonBatchNode(); 
    static void DestroySingleton(); 
    static void initBatchNodeSingleton(const char* asset); 

protected: 
    static CCSpriteBatchNode* m_singletonBatchNode; 
    static bool singletonIsInitialized; 
    static const char* assetName; 
}; 

此代碼將導致吉姆和鮑勃分享BatchNodeSingleton的保護成員。我需要他們各自擁有自己的一套。什麼是一個好的解決方案?可以通過assetName查找指針的指針集合?

會真的很感激你的想法。

+0

你是對的,我需要的是每派生的對象的層次結構類的一個實例。可能有成千上萬的吉姆,但他們都需要一個CCSpriteBatchNode – 2012-03-31 22:09:40

回答

5

CRTP是一個流行的模式:

template <typename T> struct Singleton 
{ 
    static T & get() 
    { 
     static T instance; 
     return instance; 
    } 
    Singleton(Singleton const &) = delete; 
    Singleton & operator=(Singleton const &) = delete; 
protected: 
    Singleton() { } 
}; 

class Foo : public Singleton<Foo> 
{ 
    Foo(); 
    friend class Singleton<Foo>; 
public: 
    /* ... */ 
}; 

用法:

Foo::get().do_stuff(); 
+0

輝煌的實例,謝謝! – 2012-03-31 23:03:38