在 android.support.v4.util 包下,有個類 Pools.java ,它是用來干什么的呢?我們看下這個類的功能描述:
Helper class for creating pools of objects.
超級簡單的一個介紹,就是一個創(chuàng)建對象池的幫助類。
接下來我們?nèi)タ聪逻@個類的具體實現(xiàn)代碼:
public final class Pools {
// 管理對象池的接口
public static interface Pool<T> {
// 如果對象池中有這樣的實例就返回這樣的實例否則返回null
public T acquire();
// 釋放一個實例到對象池
public boolean release(T instance);
}
private Pools() {
/* 私有化構(gòu)造函數(shù) */
}
/**
* 簡單的對象池
*
* @param <T> 對象池里保存的對象類型
*/
public static class SimplePool<T> implements Pool<T> {
private final Object[] mPool;
private int mPoolSize;
/**
* 創(chuàng)建一個新實例
*
* @param maxPoolSize 對象池的最大容量
*
* @throws IllegalArgumentException 如果對象池的容量小于0
*/
public SimplePool(int maxPoolSize) {
if (maxPoolSize <= 0) {
throw new IllegalArgumentException("The max pool size must be > 0");
}
mPool = new Object[maxPoolSize];
}
@Override
@SuppressWarnings("unchecked")
public T acquire() {
if (mPoolSize > 0) {
// 拿對象池的最后一個
final int lastPooledIndex = mPoolSize - 1;
T instance = (T) mPool[lastPooledIndex];
// 拿出對象以后,清掉對象池里保存的信息
mPool[lastPooledIndex] = null;
mPoolSize--;
return instance;
}
return null;
}
@Override
public boolean release(T instance) {
// 重復(fù)添加會拋異常
if (isInPool(instance)) {
throw new IllegalStateException("Already in the pool!");
}
if (mPoolSize < mPool.length) {
mPool[mPoolSize] = instance;
mPoolSize++;
return true;
}
return false;
}
private boolean isInPool(T instance) {
for (int i = 0; i < mPoolSize; i++) {
if (mPool[i] == instance) {
return true;
}
}
return false;
}
}
/**
* 同步的對象池
*
* @param <T> 對象池的類型
*/
public static class SynchronizedPool<T> extends SimplePool<T> {
private final Object mLock = new Object();
public SynchronizedPool(int maxPoolSize) {
super(maxPoolSize);
}
@Override
public T acquire() {
synchronized (mLock) {
return super.acquire();
}
}
@Override
public boolean release(T element) {
synchronized (mLock) {
return super.release(element);
}
}
}
}
其實從代碼的實現(xiàn)來看是非常簡單的,不過知道這個工具包的幫助類,可以為我們以后使用對象池提供更加方便的實現(xiàn)。接下來,我們看一下關(guān)于對象池的簡單使用方法:
public class MyPooledClass {
private static final SynchronizedPool<MyPooledClass> sPool =
new SynchronizedPool<MyPooledClass>(10);
public static MyPooledClass obtain() {
MyPooledClass instance = sPool.acquire();
return (instance != null) ? instance : new MyPooledClass();
}
public void recycle() {
// Clear state if needed.
sPool.release(this);
}
. . .
}