对象复用池

原文:https://github.com/libgdx/libgdx/wiki/Memory-management#object-pooling

对象池化

对象池化是重复使用未激活或者“死掉”的对象的基本原则,而不是每次都创建新的对象。可以通过创建一个对象池来实现,当你需要一个新的对象时,你可以从对象池中获取。如果池中有可用的对象,就返回,如果池是空的或者不包含可用的对象,将会创建一个新的对象的实例并返回。当你不需要一个对象时,需要进行释放,这就意味着将对象返回到池中。通过这种方式达到分配内存的重复利用。

这在游戏的内存管理中至关重要。

Libgdx提供了一系列的工具来实现简单的轮询。

  • Poolable接口

  • Pool

  • Pools
    继承Poolable接口意味着你需要在你的对象中有一个reset()方法。这个方法可以自动调用释放你的对象。

以下是一个简单的示例:

 public class Bullet implements Poolable {
public Vector2 position;
public boolean alive;
/**
 * 构造器,初始化.
 */
public Bullet() {
    this.position = new Vector2();
    this.alive = false;
}
/**
 * 初始化,从对象池中获取
 */
public void init(float posX, float posY) {
    position.set(posX,  posY);
    alive = true;
}
/**
 * 回调方法
 */
@Override
public void reset() {
    position.set(0,0);
    alive = false;
}
/**
 *更新
 */
public void update (float delta) {
    // 更新位置
    position.add(1*delta*60, 1*delta*60);
    // 屏幕之外,设置为dead
    if (isOutOfScreen()) alive = false;
}

}

在游戏的world类中:

public class World {
// Bullet类
private final Array<Bullet> activeBullets = new Array<Bullet>();
// bullet池
private final Pool<Bullet> bulletPool = new Pool<Bullet>() {
@Override
protected Bullet newObject() {
    return new Bullet();
}
};

public void update(float delta) {
    // 新的Bullet
    Bullet item = bulletPool.obtain();
    item.init(2, 2);
    activeBullets.add(item);
    //释放bullet
    Bullet item;
    int len = activeBullets.size;
    for (int i = len; --i >= 0;) {
        item = activeBullets.get(i);
        if (item.alive == false) {
            activeBullets.removeIndex(i);
            bulletPool.free(item);
        }
    }
}

}

Pools类中提供了静态方法来动态的创建任何对象的池。如下:

private final Pool<Bullet> bulletPool = Pools.get(Bullet.class);
怎样使用Pool

一个Pool<>管理一个单独类型的对象。从一个特定的Pool实例中取出,然后释放之后返回到Pool中。对象可能会实现Poolable接口,这将会在对象返回到Pool中自动进行重置。对象将按需分配。

你必须实现你自己的Pool<>子类,因为newObject方法是抽象的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值