Projects > cpp > Issues > Feature #3265

We are migrating issue tracker of Cocos2d-x Project to Github, please create new issue there. Thanks.

Create Issue on Github

Instantiating subclasses of cocos2d-x singletons

Feature #3265 [Closed]
Nyckel 2013-11-22 09:47 . Updated about 2 years ago

I sometimes find myself needing to subclass singletons, such as SpriteFrameCache (to access the protected spriteFrames member in my game editor), or EGLView . I will use SpriteFrameCache as an example.
The problem: The SpriteFrameCache::getInstance method always instantiates a SpriteFrameCache, and there is no way of asking it to create a subclass.
Proposed solution: A new static member in the singleton, which is a pointer to a new class SpriteFrameCacheCreator, is used to call a custom constructor. If the pointer is not set, the singleton will instantiate itself with new as usual.
Sample implementation:
In CCSpriteFrameCache.h OR a new file, CCSpriteFrameCacheCreator.h
class SpriteFrameCacheCreator
virtual SpriteFrameCache *
createSpriteFrameCache = 0;
In existing class cocos2d::SpriteFrameCache:
static void setSpriteFrameCacheCreator
static SpriteFrameCacheCreator***creator;

In existing file CCSpriteFrameCache.cpp:

SpriteFrameCacheCreator *SpriteFrameCache::_creator = NULL;


SpriteFrameCache* SpriteFrameCache::getInstance()
    if (! _sharedSpriteFrameCache)
            _sharedSpriteFrameCache = _creator->createSpriteFrameCache();
            _sharedSpriteFrameCache = new SpriteFrameCache();

    return _sharedSpriteFrameCache;

Finally, to use your own subclass of SpriteFrameCache, create a subclass of SpriteFrameCacheCreator and have it return a new subclass of SpriteFrameCache (where your SpriteFrameCache has a public constructor). Before your first use of SpriteFrameCache, set your creator with cocos2d::SpriteFrameCache::setSpriteFrameCacheCreator(myCreator);

If there is a simpler solution to this, that still allows SpriteFrameCache to be a singleton with a private constructor, please let me know!

Iā€™m willing to help implement it if this or another solution to the problem is accepted. 2014-10-08 02:45

Redmine issue system is closed, we are using github issue system instead.

This issue was moved to

Atom PDF

Start date:2013-11-22
Due date:
% Done:


Target version:-

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.