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
<pre>
class SpriteFrameCacheCreator
{
public:
virtual SpriteFrameCache *
createSpriteFrameCache = 0;
};
</pre>
In existing class cocos2d::SpriteFrameCache:
<pre>
public:
static void setSpriteFrameCacheCreator
private:
static SpriteFrameCacheCreator***creator;

</pre>
In existing file CCSpriteFrameCache.cpp:

SpriteFrameCacheCreator *SpriteFrameCache::_creator = NULL;

and

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

    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.

walzer@cocos2d-x.org 2014-10-08 02:45

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

This issue was moved to https://github.com/cocos2d/cocos2d-x/issues/8263

Atom PDF

Status:Closed
Start date:2013-11-22
Priority:Low
Due date:
Assignee:-
% Done:

0%

Category:-
Target version:-

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