
Design Patterns - State Pattern
Originally published on my old blog at cumps.be on August 8, 2008.
It’s been a while again, but it’s time for another pattern. Today we’ll look at the State Pattern.
First of all, the definition: “Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.”
An additional request has surfaced today: we need to keep track of whether a unit is alive or dead, and let it respond differently based on its state. Initially we solved this by introducing a new enum called UnitState and adding lots of switch statements to our code.

In the long run however, this would mean we have to keep on going into those statements whenever a new state needs to get added, which isn’t exactly following the Open/Closed Principle we talked about. Let’s refactor this and introduce a new interface called IUnitState.

Instead of using an enum, we’re going to introduce two new classes, which implement IUnitState to represent our different states.

By separating the logic for different states in different classes, we can add a new state easily, by simply creating a new class, and we keep our code base structured. For example, the simplest state looks like this:

When we pull all of this together we get the following class diagram, illustrating two concrete states and the state interface.

To the outside, whenever the internal state changes, it looks like the object, GameUnit, changed its type because a different concrete state is providing an implementation for the actions.
When we test this code, we can see the behavior of internal state changing after the first Kill() command.

I realize this isn’t the best example to illustrate the State Pattern, and I’m not entirely happy with it. Stretching the game example like that sometimes works out, and sometimes it feels a little forced, like today. I hope it made sense; be sure to check out the sites below for some other examples as well.
I’ve uploaded the solution again so you can have a look.
Some additional information on the State Pattern:
You May Also Like

Design Patterns - Composite Pattern
The Composite Pattern: tactical moves made of submoves, as a tree that the game treats as a single move.

Design Patterns - Iterator Pattern
The Iterator Pattern: one loop over two factions' orders, whether they're stored in a List or an array, and then the same with IEnumerable.

Design Patterns - Template Method Pattern
The Template Method Pattern: a base renderer that fixes the drawing order, while the 2D and 3D renderers fill in each step.



