Hi,
I'm building an app, and I need the wisdom of the SO community on a design issue.
In my application, there needs to be EXACTLY one instance of the class UiConnectionList
, UiReader
and UiNotifier
.
Now, I have figured two ways to do this:
Method 1: Each file has a global instance of that class in the header file itself.
Method 2: there is a separate globals.h file that contains single global instances of each class.
Example code:
Method 1
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
namespace Globals {
UiConnectionList connectionList;
}
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
namespace Globals {
UiNotifier uiNotifier;
}
#endif // UINOTIFIER_H
Method 2:
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
#endif // UINOTIFIER_H
file: globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
#include "uiconnectionlist.h"
#include "uinotifier.h"
namespace Globals {
UiConnectionList connectionList;
UiNotifier uiNotifier;
}
#endif // GLOBALS_H
My Question
What is the better/right way to do this?
PS: I don't think that singleton is the right answer here, is it?
Thanks
Okay, so two answers have told me to make instances of UiConnectionList
and UiNotifier
, optionally wrap it in a UiContext
and pass it around wherever required.
Could someone enumerate reasons (with examples) why passing around the context is better than having globally accessible variables.
This will help me judge what method is better (or better suited for my app).
Thanks