Individual singleton inheritance for each hierarchy
-
28-05-2021 - |
سؤال
OO Design question.
I want to inherit singleton functionality into different hierarchies of classes. That means they need to have their own instance of singleton per hierarchy.
Here is a brief example of what i am trying to do:
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;
};
This code will cause Jim and Bob to share BatchNodeSingleton's protected members. I need them to have their own set each. What would be a good solution? Collection of pointers that can be looked up by assetName as key?
Would really appreciate your thoughts.
المحلول
CRTP is a popular pattern:
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:
/* ... */
};
Usage:
Foo::get().do_stuff();
لا تنتمي إلى StackOverflow