Game Development Reference
In-Depth Information
public void free(T object) {
if (freeObjects.size()<maxSize)
freeObjects.add(object);
}
}
The free() method lets us reinsert objects that we no longer use. It simply inserts the object into
the freeObjects list if it is not yet filled to capacity. If the list is full, the object is not added, and it
is likely to be consumed by the garbage collector the next time it executes.
So, how can we use that class? We'll look at some pseudocode usage of the Pool class in
conjunction with touch events.
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);
First, we define a PoolObjectFactory that creates TouchEvent instances. Next, we instantiate the
Pool by telling it to use our factory and that it should maximally store 50 TouchEvent s. When we
want a new TouchEvent from the Pool , we call the Pool 's newObject() method. Initially, the Pool is
empty, so it will ask the factory to create a brand-new TouchEvent instance. When we no longer
need the TouchEvent , we reinsert it into the Pool by calling the Pool 's free() method. The next
time we call the newObject() method, we get the same TouchEvent instance and recycle it to
avoid problems with the garbage collector. This class is useful in a couple of places. Please note
that you must be careful to fully reinitialize reused objects when they're fetched from the Pool .
KeyboardHandler: Up, Up, Down, Down, Left, Right . . .
The KeyboardHandler must fulfill a couple of tasks. First, it must connect with the View from
which keyboard events are to be received. Next, it must store the current state of each key
for polling. It must also keep a list of KeyEvent instances that we designed in Chapter 3 for
event-based input handling. Finally, it must properly synchronize everything since it will receive
events on the UI thread while being polled from our main game loop, which is executed on a
different thread. This is a lot of work! As a refresher, we'll show you the KeyEvent class that we
defined in Chapter 3 as part of the Input interface.
public static class KeyEvent {
public static final int KEY_DOWN =0;
public static final int KEY_UP =1;
public int type;
public int keyCode;
public char keyChar;
}
 
Search WWH ::




Custom Search