How to use QNetworkAccessManager in different classes? Sharing important data between classes?

I have a MainWindow application that I am working on to learn C ++ and Qt (C ++ and QT 4.8). I want to make HTTP requests in different objects of my application, such as Dialogs / Wizard and MainWindow. I know that basically I have to have one QNetworkAccessManager for each application. My question is how to properly pass this QNAM between classes?

At the moment I have it as a pointer, I turn to the designer of my wizard, but it seems ... inelegant and inflexible. What is the correct way to give my dialogs or any other classes that I decided to make, access my one QNetworkAccessManager? I probably have the same question about any data that I need to provide to everyone.

What is a properly designed C ++ solution? A singleton pattern seems to be an option, but bad, as I understand it. I have some code to show my question.

My MainWindow constructor and the slot that launches my wizard:

MyMainWindow::MyMainWindow { qnam = new QNetworkAccessManager(); } ... MyMainWindow::wizardStarter { mywizard = MyWizard(vari, qnam, this); } 

My master constructor in which I make network requests and analyzing data after receiving data from the user, and therefore in which I need QNetworkAccessManager:

 MyWizard::MyWizard(SomeOtherArgument *vari, QNetworkAccessManager *qnam, QObject *parent) { ... this->ourQnam = qnam; ... } MyWizard::launchRequest(QUrl newUrl) { ourQnam->get(QNetworkRequest(newUrl)); } 
+6
source share
1 answer

From your question, I think you are really asking what form of dependent injection (i.e. injects your dependent QNetworkAccessManager object into objects).

In your case, you use the injection constructor . This is a well-known and accepted form of injection. It strongly tells your wizard class depends on the QNetworkAccessManager, which makes your code easy for people to understand. If you used a single singlet to simply grab a static QNetworkAccessManager from within the implementation of the wizard class, while it has the advantage of removing the constructor injection, it hides that your wizard class uses the QNetworkAccessManager.

Another well-known form of injection is setter injection setDelegate( delegate )

Professionally speaking, there is nothing wrong with your current approach, as it clearly states that your wizard class depends on the QNetworkAccessManager object.

Here is a bit of reading if you want to know more about dependency injection.

Dependency Injection

Dependency Injection in C ++

+5
source

Source: https://habr.com/ru/post/919598/


All Articles