State pattern is intended to provide a mechanism to allow an object to alter its behavior in response to internal state changes. To the client, it appears as though th object has changed its class.

image

And last, but not least, my most favorite design pattern: the State pattern. Why it is my favourite pattern? I am not sure, but I just like the fact that you can manipulate the state of an object. Once you get the idea of states, it is a very powerful way to add behavior to an object.

All the client needs to know is about a certain context and a state, which is injected into the context. Voila, the context has a state. By calling a method Request another state is requested. Nice, huh?

The abstract class State defines a method to handle the change of state within the current context.

 

Upon creation of the context a state is injected and can be changed by calling a method Request.

 

The concrete states implement how the change of state is handled.

 

I think this is a nice pattern. You can apply this pattern in many ways, for example simple workflow or wizard like pages. One example I like is that of a dataform. When it shows up there is no need to save data, since it not has been altered. As soon as data is filled in the state of the form changes and the save button is enabled.

 

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.