My game base consists of a series of modules, organized as classes, that are created, updated and interact when needed.
A few examples could be: CWindowManager
, CGraphicsManager
, CPhysicsManager
, and so on.
I'm ashamed to have to say that I currently use global pointers for them (extern CWindowManager* g_WindowManager;
), and I know that this is probably a bad thing to do.
In any case, the thing is that these modules need to be created and deleted dynamically, and that in the right order of course. Theres also the problem that modules like CPhysicsManager
are scene-dependent, therefore they are deleted when the scene is switched and then created again.
Now, I'd like to switch away from using globals for working with modules in my game.
I'm not afraid of the refactoring, but I can't really think of what would be the best alternative to globals.
I have thought about creating a CModuleManager class and storing instances of the modules in there as members, which are the开发者_JS百科n derived from a CModule base class. Although I can't really think of how this would work in detail.
This seems like a common problem in software development and especially game development, so:
- What is the best option for managing modules, compared to simply using global pointers?
Some things to consider when using global data:
- multi-threading. You need to be careful if the global data can be accessed by different threads concurrently.
- testability. If you are writing unit tests, then the global data needs to be initialized before any code accesses the global data.
An alternative to using global data is to pass the object instances that each class/method requires as a parameter. This has the benefit that all the dependencies of a class are visibly from the API. It also makes writing unit tests much easier. The disadvantage is that the code can get messy if you are passing objects all over the place.
Your idea of having a ModuleManager sounds like the Service Locator pattern - which I think is a feasible solution. This link may help: http://gameprogrammingpatterns.com/service-locator.html.
If you choose to carry on using global pointers, then dynamically deleting the global data can be achieved in C++ using smart pointers (auto_ptr).
精彩评论