What is the best way to do this
-
Imagine that I have an input where the user specify an url address, I want my application to parse that address and call the right handler for that address.
For example, I have a base class for handlers and classes that inherit from the base class. Each handler will result a string with information from that address and each handler will download the page, parse and so on...
I was wondering, is there a design pattern to help me with that? I mean, how my application know which handler to instantiate?
I don't want to be using if and elses, it seems to be a bad design.Thank you.
-
@Defohin I don't know if there is a design pattern for this but to avoid giant if/else I like to use maps.
You can do something like:
class Handler { public: void handleIt(); }; class HttpHandler : public Handler { }; class FtpHandler : public Handler { }; class X { public: X(); void doSomething(const QString &protocol); private: static QMap<QString, Handler *> handlerMap_; } // .cpp file QMap<QString, Handler *> X::handlerMap_; X::X() { // init map here if (handlerMap_.empty()) { handlerMap_["http"] = new HttpHandler; handlerMap_["ftp"] = new FtpHandler; // etc with all protocols you want to handle } } void X::doSomething(const QString &protocol) { if (!handlerMap_.contains(protocol)) return; // we dont handle that protocol auto handler = handlerMap_.value(protocol); handler->handleIt(); }
That all just came out of my head real quick so it may not compile or be 100% syntactically correct, but it should give you the idea. The map is static so it isn't built every time you instantiate your class
X
. It doesn't need to be but will be better on memory and speed if it is. :) -
That is a really nice approach, I will wait for other answers, I think that might be other ways out there.
Thank you very much. -
-
Hi,
The idea of @ambershark is simple yet effective. Good starting point for the problem you described.