思想就是一个对象只能有一个池子,用对象从池子里面取,每个池子有一个管理者来管理所对应的池子,取对象从管理者这里申请
template<class _Ty>
class ObjectPoll
{
private:
enum
{
PollSize = 4
};
protected:
struct _Node
{
_Node* next;
};
_Node* front;
_Node* rear;
void ReFull()
{
int total = sizeof(_Node) + sizeof(_Ty);
for (int i = 0; i < PollSize; ++i)
{
_Node* s = (_Node*)malloc(total);
s->next = nullptr;
new (s + 1) _Ty();
rear->next = s;
rear = s;
}
}
void Pollinit()
{
_Node* s = (_Node*)malloc(sizeof(_Node));
front = s;
rear = s;
ReFull();
}
void Clear()
{
_Node* p = nullptr;
while (front->next != nullptr)
{
p = front->next;
front->next = p->next;
free(p);
}
}
public:
ObjectPoll()
{
Pollinit();
}
~ObjectPoll()
{
Clear();
}
_Ty* allocObjectMemory()
{
if (front == rear)
{
ReFull();
}
_Node* s = front->next;
front->next = s->next;
if (s == rear) rear = front;//front一直指向头结点
return (_Ty*)((char*)s + sizeof(_Node));
}
void freeObjectMemory(void* q)
{
_Node* p = (_Node*)((char*)q - sizeof(_Node));
p->next = nullptr;
rear->next = p;
rear = p;
}
};
template<class _Ty>
class ObjectPollBase:protected ObjectPoll<_Ty>
{
private:
static ObjectPollBase<_Ty>* instance;
protected:
ObjectPollBase(): ObjectPoll<_Ty>() {};
public:
static ObjectPollBase& Getinstance()
{
if (instance == nullptr)
{
instance = new ObjectPollBase<_Ty>();
return *instance;
}
else return *instance;
}
_Ty* getobj()
{
return ObjectPoll<_Ty>::allocObjectMemory();
}
void freeobj(_Ty*& t)
{
ObjectPoll<_Ty>::freeObjectMemory(t);
t = nullptr;
}
void destory()
{
delete instance;
instance = nullptr;
}
};
template<class _Ty>
ObjectPollBase<_Ty>* ObjectPollBase<_Ty>::instance = nullptr;