大理旅游网站建设,无锡微信公众号开发,重庆企业官网设计,wordpress视频插件w代码描述#xff1a;
写了一个类#xff0c;命名为对象池#xff08;ObjectPool #xff09;#xff0c;里面放个map容器。
3个功能#xff1a;添加对象#xff0c;删除对象#xff0c;查找对象
该类只构建一次#xff0c;故采用单例模式功能描述#xff1a;对象池可…代码描述
写了一个类命名为对象池ObjectPool 里面放个map容器。
3个功能添加对象删除对象查找对象
该类只构建一次故采用单例模式功能描述对象池可以存储其他类的对象指针单例模式的头文件
#ifndef jz_singleton_h__
#define jz_singleton_h__templatetypename T
class SINGLETON
{
public:static T* get_instance(){static T instance;return instance;}virtual ~SINGLETON() noexcept {}SINGLETON(const SINGLETON) delete;SINGLETON operator(const SINGLETON) delete;protected:SINGLETON() {}
};#endif
对象池的头文件
#ifndef OBJECTPOOL_H
#define OBJECTPOOL_H#include QObject
#include QMap
#include singleton.hclass ObjectPool : public QObject,public SINGLETONObjectPool
{Q_OBJECT
public:explicit ObjectPool(QObject *parent nullptr);bool addobject(QString object_name,QObject *object);bool removeobject(QString object_name);QObject* getobject(QString object_name);private:QMapQString,QObject*object_pool_;
};#endif // OBJECTPOOL_H
对象池的cpp文件
#include objectpool.h
#include QDebug
ObjectPool::ObjectPool(QObject *parent) : QObject(parent)
{}bool ObjectPool::addobject(QString object_name, QObject *object)
{if(object_name.isEmpty()){return false;}if(objectnullptr){return false;}if(object_pool_.contains(object_name)){return false;}object_pool_.insert(object_name,object);qDebug()add object success;return true;}bool ObjectPool::removeobject(QString object_name)
{object_pool_.remove(object_name);qDebug()remove object success;return true;
}QObject *ObjectPool::getobject(QString object_name)
{return object_pool_.value(object_name);}
用法
//这里构造对象先构造父类生成单例指针。再构造子类对象池
ObjectPool *test_temp_pool dynamic_castObjectPool *(ObjectPool::get_instance());//先添加一个对象QString first(first_object);QObject *first_objectnew QObject();test_temp_pool-addobject(first,first_object);
//再删除这个对象test_temp_pool-removeobject(first);