java - 用于不同类型子对象的 Libgdx 池

标签 java memory-management libgdx

我有一个单位类及其一些子类(弓箭手、剑客等)。 我怎样才能创建一个回收所有单元类型子类的池?

最佳答案

这是不可能的,因为只能包含一种特定类型的对象。否则你可能会遇到这样的情况:

Pool<Unit> unitPool = ...;
Archer acher = new Archer();
unitPool.free(archer); // we free an Archer, who is a Unit
Unit swordsmanUnit = unitPool.obtain(); // we can obtain only Units
Swordsman swordsman = (Swordsman) swordsmanUnit; // This is actually an Archer and will result in a ClassCastException

幸运的是,libgdx 附带了一个名为 Pools 的实用程序,可以轻松池化许多不同的类。它为每个类创建一个ReflectionPool,并从正确的池中释放/获取您的对象。只需使您的 UnitPoolable 即可。

Archer archer = Pools.obtain(Archer.class);
Swordsman swordsman = Pools.obtain(Swordsman.class);
// ...
Pools.free(archer);
Pools.free(swordsman);

关于java - 用于不同类型子对象的 Libgdx 池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246559/

相关文章:

c++ - 从不直接调用 std::allocator 的成员函数是最佳实践吗?

java - 将鼠标悬停在文本上不改变颜色 - libgdx

java - 在 Java 中循环遍历数组的前 20 个元素

java - if else 语句与 try catchblock 一起抛出错误

java - 比利时荷兰语的正确货币格式是什么?

c++ - 在标题中定义 cv::Mat 后跟另一个 Mat 避免了多个 channel

c++ - C++ 如何处理递归类定义?

java存储主函数之外的类的所有对象

android - 从 Libgdx 纹理中提取 byte[]

libgdx - LibGDX如何判断当前操作系统运行的是哪种语言?