C++ | 对象池结合单例模式

思想就是一个对象只能有一个池子,用对象从池子里面取,每个池子有一个管理者来管理所对应的池子,取对象从管理者这里申请

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值