By the way, I’m not familiar with ALL the major design patterns, so some of my tricks might have names I don’t know of, in which case – fill me in!
Now, on to my favorite trick by far. You can do this in just about any language that supports inheritance.
As we all know, a pointer to an interface or base class can be assigned to any children of said class, provided you use only the methods available in the pointer’s type ( if you don’t know what I’m talking about, get a design patterns book FAST! ) One of my favorite things to break up into small encapsulated classes is the program’s interface. A game’s loading screen, game play, credits, score board, etc, are often crammed into a single driver class or even called in the main loop with a ton of conditionals. I prefer them to be in separate classes.
So try this. You have your main class with its main loop. There are a series of functions that get looped through in any mode, usually draw() and update(). Whatever the current mode is, the loop delegates to that mode and it runs until a switch is needed. Normally, programmers will have some kind of return value or other check to see when to make the switch. But I prefer to have the MODE do the switching. If update() gets called once a loop, why not have it return the next mode to switch to?
mode * nextMode = curMode->update();
if( nextMode != curMode ) {
delete curMode;
curMode = nextMode;
}
If you have some way of only keeping one of each mode ( singleton, or something else, ) simply don’t delete. This is even easier with boost’s smart pointers or your chosen language’s garbage collection. Long story short, your current mode will keep returning itself ( “ITS ME AGAIN” ) until it needs to switch, in which case it returns an instance to the appropriate mode. You can even have one return NULL for something else, say, ending the program.
This trick does not stop at game modes. Anything which delegates functionality to different child classes using the strategy pattern can use this in some form. For example, a game I am currently working on nests the use in two cases. The game’s mode is done this way, but within one of them I use the trick again, for dialog boxes. In the case of my game I don’t even need singletons or such.
I have yet to run into even a small amount of trouble doing this. Tell me what you think.