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);
相关推荐
进击ing小白3 小时前
Qt 无边框窗口进阶指南
开发语言·qt
问君能有几多愁~11 小时前
Qt Json 序列化操作
开发语言·qt·json
平常心的技术小牛11 小时前
Qt-快速上手-QFileDialog
windows·qt·microsoft
小小龙学IT12 小时前
Qt Graphics View Framework(图形视图框架)深度解析:从 Scene/View/Item 到工业级 2D 场景
开发语言·数据库·qt
程与留12 小时前
09_Qt 布局管理系统——QHBoxLayout、QVBoxLayout、QGridLayout
c++·qt
神仙别闹12 小时前
基于QT(C++)实现旅游线路规划系统
c++·qt·旅游
Java后端的Ai之路12 小时前
05、Python单例模式完全指南
开发语言·人工智能·python·单例模式·oracle
≮傷£≯√12 小时前
音量调节弹窗 自定义组件qt
开发语言·qt
小小龙学IT1 天前
Qt 6 跨平台开发完全指南:从信号槽机制到实际项目落地
开发语言·qt
丰锋ff1 天前
基于 Qt 的智能门禁系统
qt·学习