Skip to content
David Cumps
Design Patterns - State Pattern

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.

Initial State Implementation

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.

State Interface

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

Concrete 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:

State Implementation

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

State Pattern Class Diagram

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.

Testing State Pattern

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