Game Development Reference
In-Depth Information
Here are the generics: the first thing to recognize is that this is a generically typed class, much
like collection classes such as ArrayList or HashMap . Generics allow us to store any type of
object in our Pool without having to cast continuously. So what does the Pool class do?
public interface PoolObjectFactory<T> {
public T createObject();
}
An interface called PoolObjectFactory is the first thing defined and is, once again, generic. It has
a single method, createObject() , that will return a new object with the generic type of the Pool/
PoolObjectFactory instance.
private final List<T> freeObjects;
private final PoolObjectFactory<T> factory;
private final int maxSize;
The Pool class has three members. These include an ArrayList to store pooled objects, a
PoolObjectFactory that is used to generate new instances of the type held by the class, and a
member that stores the maximum number of objects the Pool can hold. The last bit is needed so
our Pool does not grow indefinitely; otherwise, we might run into an out-of-memory exception.
public Pool(PoolObjectFactory<T>factory, int maxSize) {
this .factory=factory;
this .maxSize=maxSize;
this .freeObjects= new ArrayList<T>(maxSize);
}
The constructor of the Pool class takes a PoolObjectFactory and the maximum number of
objects it should store. We store both parameters in the respective members and instantiate a
new ArrayList with the capacity set to the maximum number of objects.
public T newObject() {
T object= null ;
if (freeObjects.isEmpty())
object=factory.createObject();
else
object=freeObjects.remove(freeObjects.size() - 1);
return object;
}
The newObject() method is responsible for either handing us a brand-new instance of the type
held by the Pool , via the PoolObjectFactory.newObject() method, or returning a pooled instance
in case there's one in the freeObjectsArrayList . If we use this method, we get recycled objects
as long as the Pool has some stored in the freeObjects list. Otherwise, the method creates a
new one via the factory.
Search WWH ::




Custom Search