The state pattern
The state pattern is without doubt the most flexible of all the behavioral patterns. The pattern demonstrates how we can implement finite state machines in our code. State machines were an invention of the mathematician Alan Turing, who used them to realize all-purpose computers and prove that any mathematically computable process can be performed mechanically. In short, state machines can be used to perform any task we choose.
The mechanics of the state design pattern are simple and elegant. At any point in the life-cycle of a finite state machine, the pattern is aware of its own internal state and the current external state, or input. Based on these two properties, the machine will then produce an output (which can be none) and change its own internal state (which can be the same). Believe it or not, very sophisticated algorithms can be realized with properly configured finite state machines.
A traditional way of demonstrating the state pattern is with the example of a...