【问题标题】:Individual singleton inheritance for each hierarchy每个层次结构的单个单例继承
【发布时间】:2012-03-31 22:05:20
【问题描述】:

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

此代码将导致 Jim 和 Bob 共享 BatchNodeSingleton 的受保护成员。我需要他们每个人都有自己的一套。什么是好的解决方案?可以被assetName作为key查找的指针集合?

非常感谢您的想法。

【问题讨论】:

  • 你是对的,我需要的是每个派生对象层次结构的单个类实例。可能有成千上万的 Jim,但他们都需要一个 CCSpriteBatchNode 实例

标签: c++ oop object-oriented-analysis


【解决方案1】:

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多