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);
相关推荐
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner2 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz7 天前
QML Hello World 入门示例
qt
xcyxiner10 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner11 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner11 天前
DicomViewer (添加模型类)3
qt
xcyxiner12 天前
DicomViewer (目录调整) 2
qt
xcyxiner12 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能14 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G14 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt