slushduck
slushduck

Reputation: 193

A Design Pattern for Menu Navigation (in c/c++)

Can you recommend a Design Pattern or strategy for elegantly handling screen based menu navigation?

Where "Screen Based" means a series of interconnected full screen "pages" with buttons that link to other "Screens" -Like for example in a game's user interface.

I've implemented a State based design pattern, which I do not recommend.
The code gets messy fast and becomes prone to all sorts of state based bugs which become increasingly hard to test for.

Eg:

void Update(float dt)
{
    switch(curState)
    {
        case kScreenA:
            ScreenA.Update(dt);
            if(ScreenA.IsDone())
                curState = kScreenB;
        break;
        etc...
}

With this approach you end up needing to handle return conditions:

void Update(float dt)
{
    switch(curState)
    {
       case kScreenA:
           ScreenA.Update(dt);
           if(ScreenA.IsDone())
           {
               if(ScreenA.ReturnState == 1)
                   curState = kScreenB;
               if(ScreenA.ReturnState == 2)
                   curState = kScreenC;
               etc...
            }
     }
}

Also with this approach you may end up needing to handle entry conditions:

void InitState()
{
    switch(nextState)
    {
        case kScreenC:
            if(curState == kScreenA)
                ScreenC.InitFromA();
            if(curState == kScreenB)
                ScreenC.InitFromB();
            etc...
     }
}

So there must be a better way to design this, can you describe a better way?

Cheers,
slushduck

Upvotes: 4

Views: 6531

Answers (2)

Marius
Marius

Reputation: 216

For a simple menu system you can use the State Design Pattern. Create an interface Menu and implement it with concrete classes (FirstMenu, SecondMenu, etc). Create a MenuContext that draws the menus and has a reference of the currentSelected Menu. By using this currentSelected Menu, the ContextMenu knows to delegate the calls to the proper Menu. You can have an elegant Menu Tree as well using the State Pattern. https://en.wikipedia.org/wiki/State_pattern

Upvotes: 3

BЈовић
BЈовић

Reputation: 64253

Normal way of implementing GUIs is using MVP or presenter first. If your menu is complex with several screens, then you need several MVP trios.

Upvotes: 0

Related Questions