Qt对象池,单例模式,对象池可以存储其他类的对象指针

复制代码
代码描述:
写了一个类,命名为对象池(ObjectPool ),里面放个map容器。
3个功能:添加对象,删除对象,查找对象
该类只构建一次,故采用单例模式

功能描述:对象池可以存储其他类的对象指针

单例模式的头文件

复制代码
#ifndef jz_singleton_h__
#define jz_singleton_h__

template<typename 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.h"

class ObjectPool : public QObject,public SINGLETON<ObjectPool>
{
    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:
    QMap<QString,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(object==nullptr)
    {
        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_cast<ObjectPool *>(ObjectPool::get_instance());

//先添加一个对象
    QString first("first_object");
    QObject *first_object=new QObject();
    test_temp_pool->addobject(first,first_object);
//再删除这个对象
    test_temp_pool->removeobject(first);
相关推荐
X.Ming 同学23 分钟前
QXlsx 库在麒麟 Linux(Qt 5.15.2)下完整安装步骤(含问题排查 & 经验总结)
linux·数据库·qt
chen_22724 分钟前
qt加ffmpeg制作简易录屏工具
开发语言·qt·ffmpeg
踏过山河,踏过海42 分钟前
【Qt VS Tools在Visual Studio 2019中不起作用的解决方法】
qt·visual studio
coder_xiaoyou1 小时前
单例模式_双检锁与静态内部类
java·单例模式
ht巷子1 小时前
Qt:容器类
开发语言·c++·qt
_OP_CHEN1 小时前
【从零开始的Qt开发指南】(十三)Qt 窗口之菜单栏完全攻略:从入门到实战,打造专业级桌面应用菜单系统
开发语言·qt·前端开发·图形化界面·菜单栏·gui开发·qt窗口
小c君tt13 小时前
QT中想在QTextEdit控件中使用Qslog日志输出出现问题原因及解决方法
开发语言·qt
SunkingYang15 小时前
QT程序怎么接收MFC通过sendmessage发送的信号
qt·mfc·信号·事件·sendmessage·接收消息
SunkingYang16 小时前
Qt中QString 查找子串的完整指南
qt·字符串·qstring·子字符串·查找子串
世转神风-16 小时前
qt-在字符串中指定位置插入字符串
开发语言·qt