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);
相关推荐
_林枭_1 小时前
ZW3D二次开发_UI_ZsCcTableWidget表格控件
qt·ui·zw3d
chushiyunen1 小时前
python单例模式、大模型一次加载多次复用
开发语言·python·单例模式
橘子131 小时前
特殊类的设计
单例模式
qq_392807952 小时前
Qt 注册 C++ 给 QML 调用的几种方式
数据库·c++·qt
_林枭_2 小时前
ZW3D二次开发_UI_ZsCcTreeView树控件
qt·ui·zw3d
wumingqilin2 小时前
Qt 中使用消息中心,一处发送,其他订阅处处理逻辑
qt
MR.P_H_3 小时前
QT创建新工程,无法正常编译(Kit套件无法正常配置)
开发语言·qt
森G4 小时前
28、视图基类 QAbstractItemView---------Model/View模型视图
c++·qt
不想看见4044 小时前
C++/Qt 使用 Tushare 获取股票信息
c++·qt·信息可视化
liwenzhuola15 小时前
解决 Ubuntu 上 Qt Creator 项目编译失败的问题
数据库·qt·ubuntu