// // ObjectPool.h // DragonBall // // Created by user on 13-8-22. // // #include <iostream> #include <vector> #include "cocos2d.h" #include <algorithm> using namespace std; using namespace cocos2d; template <typename T> class ObjectPool{ public: ObjectPool(int initSize):m_initSize(initSize) { CCAssert(m_initSize >= 4, "m_initSize should >= 4"); allocate(initSize); }; virtual ~ObjectPool() { for_each(m_usedList.begin(), m_usedList.end(), freeObject); for_each(m_freeList.begin(), m_freeList.end(), freeObject); } // 请求一个对象 T* request(){ //先检查空闲里面是否为空 if (m_freeList.size() == 0) { allocate(m_initSize/2); } T* t = m_freeList[0]; m_freeList.erase(m_freeList.begin()); m_usedList.push_back(t); return t; }; // 放回一个对象到池里面 void putback(T* t) { for (int i = 0; i < m_usedList.size(); ++i) { if (t == m_usedList[i]) { //找到此对象 m_usedList.erase(m_usedList.begin() + i); m_freeList.push_back(t);return; } } } //为了避免内存的不断增长,需要保持空间 void garbage() { //打印下大小 CCLog("m_usedList.size:%d",m_usedList.size()); CCLog("m_freeList.size:%d",m_freeList.size()); //如果空余的多余20则删除到初始化个数 if (m_freeList.size() > m_initSize) { typename vector<T*>::iterator it = m_freeList.begin(); int pIndex = 0; while (it != m_freeList.end()) { if (pIndex > m_initSize) { T* t = (*it); m_freeList.erase(it); freeObject(t); --it; } ++pIndex; ++it; } } } private: // 分配size个空间 void allocate(int size) { for (int i = 0; i < size; ++i) { T* t = new T; m_freeList.push_back(t); } } static void freeObject(void* p) { T* t = (T*)p; Ref* temp = (Ref*)t; log("temp.ref : %d",temp->getReferenceCount()); delete t; } private: // 使用两个list一个用来放已经使用的,一个用来放未使用的 vector<T*> m_freeList; vector<T*> m_usedList; // 初始容量 int m_initSize; };
使用的时候 先实例化
ObjectPool<T> * objectPool = new ObjectPool<T>(size); auto pRet; if(objectPool->request()){ pRet = objectPool->request(); } else{ pRet = new T() ; } pRet->remove(); objectPool->putBack(T);
时间: 2024-11-06 21:26:41