Search code examples
c++runtime

How to choose between some methods at runtime?


In order to make my code a bit clearer, I was trying to split a long piece of code into several methods (a little PHP-like).

I have a variable CurrentStep indicating the current screen to be rendered.

class Game
{
private:
    enum Step { Welcome = 0, Menu, };
    unsigned int CurrentStep;
}

Now I want to call the corresponding method when rendering the frame:

void Game::RenderFrame
{
    switch (CurrentStep)
    {
    case Welcome:
        // the actual work is done by WelcomeScreen() to keep this clean
        WelcomeScreen(); break;
    case Menu:
        // same here
        MenuScreen(); break;
    }
}

I hope it is understandable what I was trying to achieve. Eventually it is supposed to call the appropriate method (at runtime).

However, this way is just that redundant... Isn't there a "better" way to go with C++?


Solution

  • I guess what you are looking for is the command pattern.

    Read this detailed explanation (for C++)

    http://web.archive.org/web/20120409061023/http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/

    to learn more about it.