I have next situation:
How should I share singleton from main application (2.) between plugins (3.)? Are there any features in Qt / C++ to do this?
Currently I'm using ugly solution based on shared memory and I don't think that it is right.
I'm thinking about refactoring with using of dependency injection pattern but it imposes some restrictions.
SAMPLE:
Static library "log.lib":
struct Log
{
void write( QString text );
};
Main application "app.exe":
Log *logger = new Log; // I need only one logger for all application
int main()
{
logger->write( "Main" );
...
}
Plugin 1 "plg1.dll"
extern Log *logger; // Logger from "app.exe"
void Foo()
{
logger->write( "Foo" );
}
Plugin 2 "plg2.dll"
extern Log *logger; // Logger from "app.exe"
void Bar()
{
logger->write( "Bar" );
}
Right, so in order:
I would personally just use the singleton pattern properly, and the plugin could also query the very instance. Please take a look at the following Qt macro:
Q_GLOBAL_STATIC( Type, VariableName)
Creates a global and static object of type QGlobalStatic, of name VariableName and that behaves as a pointer to Type. The object created by Q_GLOBAL_STATIC initializes itself on the first use, which means that it will not increase the application or the library's load time. Additionally, the object is initialized in a thread-safe manner on all platforms.
You could easily build the singleton pattern on top of it, and actually this would be even thread-safe.
Here you can find another example not using Q_GLOBAL_STATIC
, but QObject
inheritance and facilitates the job with QCoreApplication
that we implemented in our project.
This version above is also-thread safe.