00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #ifndef _QT_FACTORY_H
00022 #define _QT_FACTORY_H
00023
00024 #include <typeinfo>
00025
00026 #include <qmap.h>
00027 #include <qstring.h>
00028 #include <qlibrary.h>
00029 #include <qstringlist.h>
00030
00031 #define MESSAGES 0
00032
00033 template<class Base>
00034 class QFactory : private QLibrary
00035 {
00036 QMap<QString, Base *(*)()> theCreators;
00037 QMap<QString, int> theVersions;
00038 QStringList theIds;
00039
00040 public:
00042 Base *createInstance(const QString &name) { if(isOpen()) if(theIds.contains(name)) return theCreators[name](); return 0; }
00043
00045 int getVersion(const QString &name) { if(isOpen()) if(theIds.contains(name)) return theVersions[name]; return -1; }
00046
00048 const QStringList &getAvailable() { return theIds; }
00049
00051 bool isOpen() { return isLoaded(); }
00052
00054 QFactory(const QString &libPath);
00055 };
00056
00057 template<class Base>
00058 QFactory<Base>::QFactory(const QString &libPath) : QLibrary(libPath)
00059 {
00060 load();
00061 QStringList provIds;
00062 theIds.clear();
00063 if(MESSAGES) qDebug("Retrieving available classes derived from %s...", typeid(Base).name());
00064 if(resolve("getAvailable"))
00065 provIds = ((const QStringList &(*)(const QString &))(resolve("getAvailable")))(typeid(Base).name());
00066 if(MESSAGES) qDebug("Found %d candidates.", provIds.count());
00067 for(QStringList::const_iterator i = provIds.begin(); i != provIds.end(); i++)
00068 { if(MESSAGES) qDebug("Loading class %s (derived from %s)...", (*i).latin1(), typeid(Base).name());
00069 Base *(*creator)();
00070 int version = -1;
00071 creator = (Base *(*)())(resolve("create" + *i));
00072 if(resolve("version" + *i))
00073 version = ((int (*)())(resolve("version" + *i)))();
00074 if(creator && version > -1)
00075 { theIds += *i;
00076 theCreators[*i] = creator;
00077 theVersions[*i] = version;
00078 if(MESSAGES) qDebug("Loaded OK (Version: %d)", version);
00079 }
00080 }
00081 if(!theIds.size())
00082 unload();
00083 }
00084
00085 #undef MESSAGES
00086
00087 #endif