大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。
今天的微博有人讨论到对象池,我想到之前项目的实现,应该用模板来实现啊,唉,还是被前人的想法给框定了,只是实现一个特别简单,花了几分钟写了个:
const int DefaultPoolSize = 1024; template <class T> class CSSObejctPool{ private: queue<T*> m_OriBlock; queue<T*> m_ObjectBlock; const INT32 m_DefaultBlockSize; public: ~CSSObejctPool(){ while (!m_OriBlock.empty()){ T* pBlock = m_OriBlock.front(); delete []pBlock; m_OriBlock.pop(); } } CSSObejctPool(INT32 blockSize = DefaultPoolSize):m_DefaultBlockSize(blockSize){ } T* GetObject(){ if (true == m_ObjectBlock.empty()){ T* pNewObject = new T[m_DefaultBlockSize]; m_OriBlock.push(pNewObject); for (int i = 0; i < m_DefaultBlockSize; ++i){ m_ObjectBlock.push(pNewObject+i); } } T* pGetObject = m_ObjectBlock.front(); m_ObjectBlock.pop(); return pGetObject; } void ReleaseObejct(T* pObject){ if (0 == pObject){ return; } m_ObjectBlock.push(pObject); } void Clear(){ while (!m_ObjectBlock.empty()){ T* pObject = m_ObjectBlock.front(); pObject->Clear(); m_ObjectBlock.pop(); } queue<T*> tempBlock; while (!m_OriBlock.empty()){ T* pBlock = m_OriBlock.front(); for (INT32 i = 0; i < m_DefaultBlockSize; ++i){ m_ObjectBlock.push(pBlock + i); } tempBlock.push(pBlock); m_OriBlock.pop(); } m_ObjectBlock = tempBlock; } };
等下再实现个线程安全的。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/118737.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...