管理模块类的最佳选择
我的游戏库由一系列模块组成,这些模块按类组织,在需要时创建、更新和交互。
一些示例可以是:CWindowManager
、CGraphicsManager
、CPhysicsManager
等。
我很惭愧地说,我目前对它们使用全局指针(extern CWindowManager* g_WindowManager;
),而且我知道这可能是一件坏事。
无论如何,问题是这些模块需要动态创建和删除,并且当然要按照正确的顺序。还有一个问题是像CPhysicsManager
这样的模块是依赖于场景的,因此当场景切换然后再次创建时它们会被删除。
现在,我想不再使用全局变量来处理游戏中的模块。
我并不害怕重构,但我真的想不出最好的选择是什么到全局变量。
我考虑过创建一个 CModuleManager 类并将模块的实例存储在其中作为成员,然后从 CModule 基类派生。虽然我真的无法想象这将如何详细运作。
这似乎是软件开发尤其是游戏开发中的常见问题,因此:
- 与简单地使用全局指针相比,管理模块的最佳选择是什么?
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 then 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用全局数据时需要考虑的一些事项:
使用全局数据的另一种方法是传递每个类/方法所需的对象实例作为参数。这样做的好处是,类的所有依赖项都可以从 API 中看到。它还使编写单元测试变得更加容易。缺点是如果您到处传递对象,代码可能会变得混乱。
您拥有 ModuleManager 的想法听起来像服务定位器模式 - 我认为这是一个可行的解决方案。此链接可能会有所帮助:http://gameprogrammingpatterns.com/service-locator.html。
如果选择继续使用全局指针,那么在C++中可以使用智能指针(auto_ptr)来实现动态删除全局数据。
Some things to consider when using 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).