QFSFileEngine相关
Qt中设计模式随处可见。
QFSFileEngine is the default file engine for accessing regular files. It is provided for convenience; by subclassing this class, you can alter its behavior slightly, without having to write a complete QAbstractFileEngine subclass. To install your custom file engine, you must also subclass QAbstractFileEngineHandler and create an instance of your handler.
[from api document]
一图胜千言:
To install an application-specific file engine, you subclass QAbstractFileEngineHandler and reimplement create().
class ZipEngineHandler : public QAbstractFileEngineHandler { public: QAbstractFileEngine *create(const QString &fileName) const; }; QAbstractFileEngine *ZipEngineHandler::create(const QString &fileName) const{ // ZipEngineHandler returns a ZipEngine for all .zip files return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; }
When you instantiate the handler (e.g. by creating an instance on the stack or on the heap), it will automatically register with Qt. (The latest registered handler takes precedence over existing handlers.)
例如:
int main(int argc, char **argv) { QApplication app(argc, argv); ZipEngineHandler engine; MainWindow window; window.show(); return app.exec(); }
原因是:
00129 QAbstractFileEngineHandler::QAbstractFileEngineHandler() 00130 { 00131 QMutexLocker locker(fileEngineHandlerMutex()); 00132 fileEngineHandlers()->prepend(this); 00133 }
即在构造函数中将自己注册到fileEngineHandler中。
QAbstractFileEngine * QAbstractFileEngineHandler::create
(
const QString &
fileName
)
const [pure virtual]
Creates a file engine for file fileName. Returns 0 if this file handler cannot handle fileName.
Example:
QAbstractSocketEngine *ZipEngineHandler::create(const QString &fileName) const { // ZipEngineHandler returns a ZipEngine for all .zip files return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; }
而:
00175 QAbstractFileEngine *QAbstractFileEngine::create(const QString &fileName) 00176 { 00177 QMutexLocker locker(fileEngineHandlerMutex()); 00178 00179 // check for registered handlers that can load the file 00180 for (int i = 0; i < fileEngineHandlers()->size(); i++) { 00181 if (QAbstractFileEngine *ret = fileEngineHandlers()->at(i)->create(fileName)) 00182 return ret; 00183 } 00184 00185 // fall back to regular file engine 00186 return new QFSFileEngine(fileName); 00187 }回到工厂模型的定义: