內(nèi)存優(yōu)化中蜀铲,如果某個(gè)對(duì)象經(jīng)常創(chuàng)建那樣會(huì)非常損耗內(nèi)存資源郑象。
massage 對(duì)象經(jīng)常使用铝量,他提供了obtain() 方法來(lái)獲取message對(duì)象,那么其實(shí)他不是每次都去創(chuàng)建對(duì)象银亲,而是使用對(duì)象池去保存慢叨。
下面使用對(duì)象池的使用:
package com.example.xieqiping.cn.testdomejsonliyihang;
import android.support.v4.util.Pools;
import android.util.Log;
/**
* Created by xieqiping on 2017/4/9.
*/
public class TestClass {
public String name="TestClass";
static final String tag="TestClass";
private static final Pools.SynchronizedPool<TestClass> sPool=new Pools.SynchronizedPool<TestClass>(1);//對(duì)象池
//獲取對(duì)象中數(shù)據(jù)
public static TestClass obtain(){
TestClass acquire = sPool.acquire();
if (acquire==null){
Log.i(tag, "init class");
return new TestClass();
}
return acquire;
}
//清空對(duì)象
public void recycle(){
sPool.release(this);
}
}
調(diào)用測(cè)試:
TestClass testClass = new TestClass();
Log.i(TAG, "name: "+testClass.name);
testClass.name="new name";
testClass.recycle();// 回收起來(lái)備用
TestClass obtain = TestClass.obtain();
Log.i(TAG, "name: "+obtain.name);
TestClass obtain1 = TestClass.obtain();
Log.i(TAG, "name: "+obtain1.name);