1 package aurelienribon.tweenengine; 2 3 import java.util.ArrayList; 4 5 /** 6 * A light pool of objects that can be resused to avoid allocation. 7 * Based on Nathan Sweet pool implementation 8 */ 9 abstract class Pool<T> { 10 private final ArrayList<T> objects; 11 private final Callback<T> callback; 12 create()13 protected abstract T create(); 14 Pool(int initCapacity, Callback<T> callback)15 public Pool(int initCapacity, Callback<T> callback) { 16 this.objects = new ArrayList<T>(initCapacity); 17 this.callback = callback; 18 } 19 get()20 public T get() { 21 T obj = null; 22 try { 23 obj = objects.isEmpty() ? create() : objects.remove(0); 24 } catch (Exception e) {} 25 if (obj == null) obj = create(); 26 if (callback != null) callback.onUnPool(obj); 27 return obj; 28 } 29 free(T obj)30 public void free(T obj) { 31 if (obj == null) return; 32 33 if (!objects.contains(obj)) { 34 if (callback != null) callback.onPool(obj); 35 objects.add(obj); 36 } 37 } 38 clear()39 public void clear() { 40 objects.clear(); 41 } 42 size()43 public int size() { 44 return objects.size(); 45 } 46 ensureCapacity(int minCapacity)47 public void ensureCapacity(int minCapacity) { 48 objects.ensureCapacity(minCapacity); 49 } 50 51 public interface Callback<T> { onPool(T obj)52 public void onPool(T obj); onUnPool(T obj)53 public void onUnPool(T obj); 54 } 55 }