2

OO デザインの質問です。

シングルトン機能をクラスのさまざまな階層に継承したいと考えています。つまり、階層ごとに独自のシングルトンのインスタンスが必要です。

これが私がやろうとしていることの簡単な例です:

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 がキーとして参照できるポインタのコレクション?

あなたの考えを本当に感謝します。

4

1 に答える 1

6

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();
于 2012-03-31T22:12:12.427 に答える