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.
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?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Client { static void Main() { State state = new FirstConcreteState(); Context context = new Context(state); Console.Write(context.State.GetType().Name + "->"); context.Request(); Console.Write(context.State.GetType().Name + "->"); context.Request(); Console.WriteLine(context.State.GetType().Name); Console.ReadKey(); } } |
The abstract class State defines a method to handle the change of state within the current context.
|
1 2 3 4 5 |
abstract class State { public abstract void Handle(Context context); } |
Upon creation of the context a state is injected and can be changed by calling a method Request.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Context { public Context(State state) { this.State = state; } public State State { get; set; } public void Request() { this.State.Handle(this); } } |
The concrete states implement how the change of state is handled.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class FirstConcreteState : State { public override void Handle(Context context) { context.State = new SecondConcreteState(); } } class SecondConcreteState : State { public override void Handle(Context context) { context.State = new FirstConcreteState(); } } |
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.
Comments