栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

template
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 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
ObjectPollbase<_Ty>* ObjectPollbase<_Ty>::instance = nullptr;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780028.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号