Chap02-CRTP2ImplementHttpManager

Chap2-CRTP2ImplementHttpManager

SingletonTemplate

​ 我们实现发送信息的功能,采用了HTTP协议.大多数情况下,http发送管理类是一个单例类.因此为了之后的复用,我们先是实现了一个单例的模板类,在使用CRTP的形式使HttpManager继承这个模板类.

​ 模板类的形式如下:

#ifndef SINGLETON_H
#define SINGLETON_H

#include "global.h"

template<typename T>
class Singleton{
protected:
    Singleton()=default;
    ~Singleton() = default;
public:
    Singleton(const Singleton<T>&)=delete;
    Singleton&operator=(const Singleton<T>&)=delete;
    static std::shared_ptr<T>& GetInstance(){
        static std::shared_ptr<T> _instance = std::shared_ptr<T>(new T);
        return _instance;
    }

};

#endif

​ 由于使用了模板,所以这是一个纯头文件.接下来就要让我们的HttpManager继承这个单例类.

#ifndef HTTPMANAGER_H
#define HTTPMANAGER_H

#include "Properties/singleton.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QObject>
#include <QUrl>
#include <QString>
#include <QJsonObject>
#include <QJsonDocument>

class HttpManager : public QObject,public std::enable_shared_from_this<HttpManager>,public Singleton<HttpManager>
{
    Q_OBJECT
public:
    ~HttpManager();
private:
    friend class Singleton<HttpManager>;
    HttpManager();
public:
    void PostHttp(const QUrl&url,const QJsonObject&json,RequestType request_id,Modules mod);
private:
    QNetworkAccessManager _manager;
private slots:
    void do_http_finished(RequestType requestType,const QString&res,ErrorCodes errorCode,Modules mod);
signals:
    void on_http_finished(RequestType requestType,const QString&res,ErrorCodes errorCode,Modules mod);
    void on_get_code_finished(RequestType requestType,const QString&res,ErrorCodes errorCode);
};

#endif // HTTPMANAGER_H

​ 首先为了能够使用qt的信号与槽的机制,我们要继承QObject,并且添加宏Q_OBJECT.同时为了防止智能指针在使用的过程中被异常析构,我们继承std::enable_shared_from_this可以允许增加对自己的引用计数.其次继承了Singleton,使得整体只有一个HttpManager类.

结构调整

​ 为防止之后代码过多导致所有的文件堆积在了一起,我们将文件进行了分层,如下

image-20251012123710744

​ 其中最顶层存放最终的全局的管理类,主窗口和main.cpp.

​ 对于LoginInterface,存放关于登陆/注册/忘记密码界面等的代码文件.而之后可能出现的聊天界面等等皆以此形式出现.

​ Properties文件存放公共的属性,枚举等.

posted @ 2025-12-24 23:16  大胖熊哈  阅读(1)  评论(0)    收藏  举报