package com.badlogic.androidgames.framework; import java.util.ArrayList; import java.util.List; public class Pool<T> { public interface PoolObjectFactory<T> { public T createObject(); } private final List<T> freeObjects; private final PoolObjectFactory<T> factory; private final int maxSize; public Pool(PoolObjectFactory<T> factory, int maxSize) { this.factory = factory; this.maxSize = maxSize; this.freeObjects = new ArrayList<T>(maxSize); } public T newObject() { T object = null; if (freeObjects.isEmpty()) object = factory.createObject(); else object = freeObjects.remove(freeObjects.size() - 1); return object; } public void free(T object) { if (freeObjects.size() < maxSize) freeObjects.add(object); } }
下面是使用方法
PoolObjectFactory <TouchEvent> factory = new PoolObjectFactory <TouchEvent> () { @Override public TouchEvent createObject() { return new TouchEvent(); } }; Pool <TouchEvent> touchEventPool = new Pool <TouchEvent> (factory, 50); TouchEvent touchEvent = touchEventPool.newObject(); . . . do something here . . . touchEventPool.free(touchEvent);
当我们想从对象池类中创建一个新的TouchEvent对象时,我们调用newObject(),起初,对象池是空的,因此我们可以使用factory创建一组对象.
当我们不再需要TouchEvent时,我们调用对象池类的free方法,将它重新插入对象池中.这样当下次我们需要再次使用到TouchEvent实例时,
我们调用对象池的newObject时,就可以得到与上次调用时相同的实例,这样就可以循环的使用对象从而避免垃圾回收的问题了.