Applying the State Design Pattern to Real-World Scenarios

In my previous article, I wrote about the Singleton Design Pattern and a possible real-world application for it. In this article, I will do the same for the State Pattern. In addition, I will use the example from my previous post to implement the states in my state machine. But I cannot start showing examples unless I help you understand first the basic concept of this topic.

The first question I must answer is what is the State Design Pattern.

What is the State Design Pattern?

The State Design Pattern is one of the original Design Patterns proposed by the Gang of Four (GoF). The pattern falls under the Behavioral classification or category. This means that the purpose of this design is to come up with a scheme to control the behavior of objects. Specifically, it is used to model behavior of objects that must behave like a state machine. A state machine is a device that can be in one of a set number of stable conditions depending on its previous condition and on the values of its inputs, or stimuli.

When to use State Pattern

To understand this definition, consider a turnstile. A typical (simple) turnstile is a machine that can be in one of three states at any given time: locked, unlocked, and rotating. The transition from one state to another is predefined and can only occur if a proper stimulus or input is applied. For example, to transition from locked to unlocked, the turnstile must receive a coin. Assuming that the turnstile doesn't have some sort of time out feature, it will remain on that state until a proper stimulus or input is received. From this state, a push is the expected input to transition from unlocked to rotating. The turnstile will remain in the rotating state until one revolution is achieved and then will return to the locked state; where it will remain until a valid input (coin) is received and so on...

From the example above, you can see that a state machine has:

  1. A predefined (finite) number of states
  2. Predefined condition(s) to trigger a transition
  3. Specific path(s) to the next state - and maybe to a previous state
State machines are definitely procedural. That said, your code doesn't have to be. But you can use object-oriented constructs to achieve that same behavior and that is what the State Design Pattern does. I have used the state pattern many times in my career. From all of the real-world applications I have developed in the past using this pattern, the one that makes the most sense is using it to control the behavior of a wizard.

Part III of this blog will be the conclusion. In that blog, I will show some UML diagrams as well as some code examples on how to create a simple wizard using Singleton and State Design Patterns.

Stay tuned!

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example