Design patterns – State 1


State pattern is very important and, when faced with the usual implementation of  “a state machine” (enum + switches) we should consider refactoring to use this design pattern instead, especially if we consider from start that we will have many state-dependent functions and/or if we expect changes into the states (which is almost always true!).

The usual enum+switch implementation is the following:

But let’s say we have to add new states…Starting? Stopping? We will need to add more cases into the switch..and that’s only one function! what if we have multiple functions that change based on the state we’re on? That’s a whole mess for maintaining the code.

The state pattern implies that we have an interface that contains functions dependent on the state, and for each state we will have a separate class that inherit from interface, and override those virtual functions.

The full code can be found at the following link:

Leave a comment

Your email address will not be published.

One thought on “Design patterns – State