A design pattern question

Started by
2 comments, last by Hodgman 11 years, 7 months ago
Ok I've got main engine app object, and there shoud be only one instance of it. There are many subsystems (resource cache, asset manager, scene graph, etc). Which is the best way to access and create them.(All of them can have only one instance)

Currently I'm using 2 static global object for each system + a static get method.
static AssetManager * g_pAssetManager = NULL;
static AssetDestructor g_AssetManagerDestructor; // omfg I could have used boost's shared ptr to remove this class...
static AssetManager * const AssetManager::Get();

On Get() I'm checking if g_pAssetManager = NULL and allocate it. Then I return the ptr;
g_AssetManagerDestructor just check if g_pAssetManager is different than NULL and delete it;

However some systems are using another systems in their destruction process and this can cause runtime failure(destory A.destroy B using A's methods)

Any ideas how I can keep these sytems so I can control their destruction order?
(I have tried something with the resource cache already. To save some headaches and saved the get method, but I moved the global pointer into the engine app object. So it is actually doing:
[source lang="cpp"]static ResourceCashe * const ResourceCache::Get()
{
return RandomEngineApp::Get()->GetResCache();
}[/source]
Any suggestions? I've got poor design pattern knowledge(only factories, I've heard of singleton pattern but I'm not really sure if I'm using it tongue.png)
Advertisement
Yea you're using singleton pattern, and seeing some problems what they can cause. If you create the systems normally and give global access to them, you can control the construction and destruction orders.


// AssetManager.h file
class AssetManager {};
// Global accessor.
AssetManager& DefaultAssetManager();
void SetDefaultAssetManager(AssetManager* manager);

// AssetManager.cpp
namespace {
AssetManager* g_DefaultAssetManager = 0;
}
AssetManager& DefaultAssetManager()
{
assert(g_DefaultAssetManager);
return *g_DefaultAssetManager;
}
void SetDefaultAssetManager(AssetManager* manager)
{
g_DefaultAssetManager = manager;
}

// main.cpp
#include "AssetManager.h"
int main()
{
{
// Here you manage the lifetime of these objects, aswell construction
// and destruction order.
AssetManager manager;
SetDefaultAssetManager(manager);
OtherSystem system(manager);
}
SetDefaultAssetManager(nullptr);
}
Yeah really nice. I;ve seen this in many other project. I think it will be perfect for me.
Thanks.
Singleton is an anti-pattern, and should be avoided. It's really just a global variable, which is also evil, and should be avoided.
Any ideas how I can keep these sytems so I can control their destruction order?
Destruction order is normally the opposite of construction order, which works fine:class App
{
App() : a(), b(a) {};
//~App() calls b->~(), then a->~()
UsedByOthers a;
DependsOnA b;
};

This topic is closed to new replies.

Advertisement