当前位置:   article > 正文

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

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

功能描述:对象池可以存储其他类的对象指针
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

单例模式的头文件

#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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

对象池的头文件

#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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

对象池的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);

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

用法:

//这里构造对象,先构造父类,生成单例指针。再构造子类对象池
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/465946
推荐阅读
相关标签
  

闽ICP备14008679号