michaelslab

With Java i am used to the factory pattern. Since i haven't been using C++ for about a decade i thought it is time to demonmstrate a features i am used to in Java in C++ as well.

The Model

The intention of this example is to provide an environment where you can formualte the execution logic independant from the main execution logic. 

int main() {
    app::MyComponent myComponent;  // this is _my_ component
    app::ContextFactory factory;
    app::IAppContext* ctx ;
    
    // registering a component which is exepcted to work on it execution context.
    app::Register(COMPONENT_TYPE_ID,&myComponent);                      // (1)

    // create a new execution context and run it (myComponent).
    ctx = (app::IAppContext*) factory.createContext(COMPONENT_TYPE_ID); // (2)
    bool result = ctx->run();                                           // (3)

    return 0;
}

Application code in form of a component is being pluged in by means of the Register method (1).  In (2) an instance of the component is newly created. At (3) the code of the component is executed using the execution context ctx.  

When to use?

A typical application is for example a game engine. The core algorithm of the game is basically to play a game with differently structured players. A player would be represented by a component and the key algorithm of the game would be an iteration over the players joining the game.

Another example could be some kind of file consisting of records which needs to be interpreted and for each record type you requiere different code. The nice thing about this approach is that you can add new interpretations without modifying the overall logic.

 

Framework

The core elements of the framework are abstract classes like IComponent and IAppContext. 

In order to use the piece of code you need to implement IComponent and IAppContext. The semantic of IComponent provides the abstraction of a component. A software component provides a method to create an instance and a method which provides the actual execution logic of the component. The logic is expected to work only on the data which is provided by derivations of the IAppContext class. The component class needs to be registered together at the factory with some kind of unigue id which is a string (std::string) in this implementation.

If this is done you can create a new application context (IAppContext) using the key at the factory as shown above in step (2) and run the component on it by (3). It is up to the user of the framework to store the execution context at a save place.

 

The Source Code

The source code is maintained at github.com in the git repository  https://github.com/merdmann/FF.git.