Pri*_*oid 2 c++ oop object-oriented-analysis
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;
};
Run Code Online (Sandbox Code Playgroud)
此代码将导致Jim和Bob共享BatchNodeSingleton的受保护成员.我需要他们各自拥有自己的套装.什么是一个好的解决方案?可以通过assetName作为键查找的指针集合?
真的很感激你的想法.
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:
/* ... */
};
Run Code Online (Sandbox Code Playgroud)
用法:
Foo::get().do_stuff();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |