开发者

Extend a application with out changing main method?

开发者 https://www.devze.com 2023-01-22 13:43 出处:网络
I need to extend several class in my c++ application without changing any co开发者_StackOverflow社区de in application. (Product extend as a solution). Is there a specific design pattern to do that?You

I need to extend several class in my c++ application without changing any co开发者_StackOverflow社区de in application. (Product extend as a solution). Is there a specific design pattern to do that?


Your question is a bit vague. In order to extend an application without changing any code, the application would have to provide a specific mechanism for extensibility, e.g. a plug-in system.


That depends on what can of extensibility you want. Would it be ok if the extension requires re-linking the code? If it's ok then you can use a factory method and polymorphism.

struct Extension {
    virtual ~Extension() { }
    // ...
};

Extension* load_extension()
{
    ifstream config_file(".conf");
    string line;
    getline(config_file, line);
    if( line == "this extension" ) return new ThisExtension();
    else if( line == "that extension" ) return new ThatExtension();
    // else if ...
    else return NoExtension();
}

Here, to create a new extension all you need to do is subclass from Extension and add a line to the factory method. That's re-compiling one file and relinking the project.

If it is not ok to re-link the application then you can load a dynamic library at runtime.

0

精彩评论

暂无评论...
验证码 换一张
取 消