版本1: 需求:可以取得和归还池对象,池对象组织形式为先进先出 (FIFO),队列中池对象的个数要有上限, 可以管理不同类型的池对象。
设计: 对象池类设计为模板类型, 使用queue存储池对象, 提供borrowObject(),和 returnObject() 两个接口函数。
#include<iostream>
#include<string>
#include<deque>
using namespace std;
class Point
{
int _x;
int _y;
public:
Point() :_x(0), _y(0) {}
Point(int x, int y) :_x(x), _y(y) {}
void Print() const
{
cout << "X: " << _x << " Y: " << _y << endl;
}
void SetX(int x) { _x = x; }
void SetY(int y) { _y = y; }
int GetX() const { return _x; }
int GetY() const { return _y; }
};
///
// 简单日志
#define LOG(info) \
cout << __FILE__ << ":" << __LINE__ << " " \
<< __TIMESTAMP__ << " : " << info << endl;
const int MaxObjectNum = 10;
template<class T>
class ObjectPool
{
private:
bool needClose; // 需要关闭标记
std::deque<T*> m_object_queue; // 存储池对象
public:
ObjectPool() :needClose(false) {}
ObjectPool(const ObjectPool&) = delete;
ObjectPool& operator=(const ObjectPool&) = delete;
~ObjectPool()
{
Close();
}
void Close() // 关闭对象池
{
needClose = true;
Clear();
}
void Clear() // 清空对象池
{
for (auto x : m_object_queue)
{
delete x;
}
}
size_t GetNumIdle() const
{
return m_object_queue.size();
}
void Init(size_t num)
{
if (needClose)
{
LOG("对象池已关闭");
exit(1);
}
if (num <= 0 || num > MaxObjectNum)
{
LOG("创建对象个数错误");
exit(1);
}
for (size_t i = 0; i < num; ++i)
{
// 添加对象
m_object_queue.push_back(new T());
}
}
public:
T* borrowObject() //借对象
{
if (m_object_queue.empty())
{
LOG("队列已空无对象可借");
return nullptr;
}
// 将队列中的对象借出
T* tmp = m_object_queue.front();
m_object_queue.pop_front();
return tmp;
}
void returnObject(T* p)
{
if (nullptr == p)
{
LOG("借出对象丢失或提供了nullptr 指针");
return;
}
m_object_queue.push_back(p);
LOG("对象已经归还");
}
};
// 测试
int main()
{
ObjectPool<Point> objpool;
objpool.Init(2);
Point* p1 = objpool.borrowObject();
Point* p2 = objpool.borrowObject();
Point* p3 = objpool.borrowObject();
Point* p4 = objpool.borrowObject();
Point* p5 = objpool.borrowObject();
//
objpool.returnObject(p1);
objpool.returnObject(p2);
objpool.returnObject(p3);
objpool.returnObject(p4);
objpool.returnObject(p5);
return 0;
}