The state pattern is very powerful indeed. It facilitates breaking your program code into discrete states. This approach has been used successfully in the telecom industry for decades to produce what is arguably the most solid software in the world. As you can see, it’s pretty easy to implement state management in C++. With it, you have the ability to add code in a very structured fashion—just create a new State subclass interface and implementation file pair. Then just add this code wherever you need it in the program, as in Listing 8.
The state pattern can be used effectively with a small investment in coding. The source code for this article consists of five C++ header files and five accompanying C++ implementation files. To build this code and try it for yourself, just create a Visual C++ console project, drop the files in, switch off precompiled headers, and away you go!