Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Design Pattern — State

8 min readJan 9, 2021

--

An in-depth discussion on State Design Pattern

State Design pattern is one of the most common behavioral patterns — and for good reason. Any application that moves through distinct modes of operation (playing, paused, stopped; draft, submitted, approved) is managing state. This pattern gives that state management a clean structure.

What is the State Design Pattern?

State is a Behavioral Design pattern documented by the Gang of Four(GoF). It is closely related to the Finite-State Machine(FSM) — it can actually be called an application of FSM in object-oriented code.

The core idea: an object should change its behavior when its internal state changes. Instead of using a mesh of if-else statements to track what state you’re in and what each action should do, you encapsulate each state in its own class. Each state class defines the behavior for that specific state.

This follows the Open-Closed Principle — you can add new states without modifying existing ones.

Examples

Press enter or click to view image in full size
Photo by Elion Jashari on Unsplash

Instances where you may have seen or used State Design pattern —

  • BoomBox — You hit play, it starts playing. Hit pause, it pauses. Hit stop, it stops. Each button does something different depending on the current state. We’ll use this as our working example throughout this post.
  • Vending machine — Waiting for money, money inserted, item selected, dispensing. Each state has different valid actions.
  • Document workflow — Draft, Under Review, Approved, Published. Each state determines who can edit, who can approve, and what transitions are allowed.
  • Java Thread — A Thread in Java goes through states: New, Runnable, Blocked, Waiting, Terminated. The behavior of start(), interrupt(), etc. depends on the current state.
Press enter or click to view image in full size
Photo by yechan park on Unsplash

State diagram

The State Design pattern maps naturally to a state diagram. Here’s the BoomBox represented as one:

State diagram for BoomBox

Each circle is a state. Each arrow is a transition triggered by an action. Not all transitions are valid — you can’t go from Playing to Playing, and you can’t pause something that’s already stopped. These constraints are what the State Design pattern enforces cleanly.

Implementing State machine

A very basic implementation of the State machine is as follows —

To run the aforementioned class, we can use the code from below —

The output of the above code is —

Take a closer look at the BoomBox class from above. This is an example of how you would implement a state machine. This example implements a State machine with three states — Playing, Paused & Stopped. To transition from one state to another there are a few checks we need to perform. As not all transitions are supported. e.g. You cannot get from Playing to Playing. Funny but, it is correct. On a BoomBox, if you hit play, when it is already playing, nothing is expected to happen. Another example of state restriction is, if the BoomBox is in the stopped state, nothing will happen if you try to pause it. The state diagram above can confirm these restrictions.

The implementation shown above is not ideal. It implements the State machine but not the State Design Pattern.

Problems with the naive approach

  • Mesh of if-else statements — In a very simple state machine like above, we ended up with a mesh of if-else statements. Imagine when we have many more states and many more transitions. It will be very complicated to cover all the scenarios. Even the code is not readable with a simple state machine like this one.
  • Solution not extensible — We currently have only three states in our machine. When we try to add a fourth and fifth, we will have to go and re-evaluate our play(), pause() & stop() methods. We need to make sure all the combinations are covered. Add a few more if-else condition. Soon this becomes impossible to manage.
  • Violation of Design principles — Design principles like Single responsibility & Open-close principles is violated. We are doing more than one thing in the BoomBox class and we cannot introduce new states without changing the existing code.

UML Diagram

Here is the UML for the State Design pattern applied to our BoomBox example. The BoomBox is the Context class. The State interface defines the actions — play(), pause() and stop(). Each concrete state (StatePlaying, StatePaused, StateStopped) implements those actions differently.

UML diagram for State Design Pattern

Implementation of State Design Pattern

Step 1 — The State interface

We are trying to implement the State machine as mentioned above using the State Design pattern. We will keep the BoomBox class and modify it according to the requirements of the State Design patterns. We are also keeping the test code in the void main as it is. Let us start by introducing the State interface.

These methods loosely correspond to the methods in the BoomBox interface. Though we did not program to an interface, had we created a BoomBox interface, we would find these methods there.

Get Vivek Mittal’s stories in your inbox

Join Medium for free to get updates from this writer.

Now our BoomBox example can be in one of the three states — playing, paused or stopped. We will implement this interface in three classes representing the states.

Step 2 — StatePlaying

A state will decide if a command to switch to another state is feasible or not. Example the StatePlaying class will hold the logic of what to do when we get a command to change the state. e.g. If we are in Playing state, we do not want to do anything when we get a play command. Similarly, what actions are needed to go to the pause or stop state is decided in the StatePlaying class. Same applies to other state classes of the BoomBox. Every state may have a different logic & rules for state transition.

Step 3 — StatePaused

Step 4 — StateStopped

Step 5 — The modified BoomBox

Now we will modify the BoomBox class to accommodate the change in the states. Earlier implementation was based on static ints and now we have separate classes for states.

Look at the code here for play(), pause() & stop() methods. It is just calling a method of the same name on the state object. state holds the current state object.

In the beginning, the state is initialized to stop state object(stateStop). When play method on the BoomBox is called, it calls the play method on stop state object.

Now, look at the implementation of the play method in StateStopped. There we update the BoomBox state to playing and log ‘playing’. This could easily be an actual logic to play the BoomBox.

Now imagine if we call the stop method on the BoomBox and we are already in Stopped state. Look at the stop() method in the StateStopped. See how we just log a message that we are already in the stopped state. This kind of logic is part of the State-specific implementation.

Problems addressed by State Design pattern

The State Design pattern solves the following problems —

  • Behavior changes with state — An object changes its behavior when its internal state changes, without external code needing to track the state.
  • State-specific behavior is isolated — Each state is defined independently. Adding new states does not affect the behavior of existing states.
  • Eliminates conditional complexity — Replaces growing if-else or switch blocks with clean, focused state classes.
  • Single Responsibility — Each state class is responsible for one state’s behavior only.
  • Easy to extend — Adding a new state (e.g., “Fast Forward”) means creating one new class. No existing state classes change.

Issues with State Design Patterns

Some trade-offs to be aware of. None are severe — the pattern does more good than bad.

  • Complicates the design — In a small state machine example, it complicates the design by introducing several new classes. Sometimes, only some int and few ifs could do the job. But if we employ state pattern, we may be doing an overkill using the State Design pattern.
  • Need to know all the states — Even though State design pattern is pretty extendible to accommodate an increasing number of states, it is always helpful we do a proper workup at the design phase and identify all the possible states before we start implementing.
  • Routing class — Context class like in our case the BoomBox class becomes a simple routing class without any logic of its own. All the logic resides in the state-specific classes.

When to use the State Design Pattern?

  • Distinct modes of behavior — When an object acts differently depending on its current state and you have more than 2–3 states.
  • Growing conditionals — When your methods are full of if (state == X) checks and they keep growing with every new state.
  • Valid transitions matter — When not all actions are valid in all states. You can’t pause something that’s stopped. You can’t dispense without money inserted.
  • New states are likely — When you anticipate adding more states over time and need the design to accommodate that without rewriting existing logic.

You don’t need this pattern for simple boolean toggling (on/off). A single boolean and an if-else is simpler and clearer.

State vs. Strategy

State and Strategy are structurally identical — both use composition and delegation through an interface. The difference is intent:

  • State — the object changes its own behavior internally as its state transitions. The switching is automatic and driven by the object itself.
  • Strategy — the client explicitly picks which behavior to use. The selection is external.

If the object changes its own behavior → State. If the client chooses the behavior → Strategy.

Summary

  • Implementation of Finite State Machine in object-oriented code
  • Allows for different behavior based on the internal states
  • Very easy to add new state — extendible without modifying existing states
  • Simplifies spaghetti code, reduces cyclomatic complexity
  • A large number of small classes involved
  • Closely related to Strategy — same structure, different intent. State transitions are internal; Strategy selection is external.

Conclusion

State is one of the most intuitive GoF patterns because it mirrors how we already think about systems — a machine is in a state, and what it does depends on that state. The pattern just formalizes that thinking into clean, isolated classes.

The BoomBox example is simple, but the same structure scales to complex workflows — order processing, document approvals, game AI. The value shows up when the fourth or fifth state gets added and no existing state class is touched.

If you find yourself writing if (state == PLAYING) more than twice in the same class, it’s time to reach for State.

Press enter or click to view image in full size
Photo by Katya Austin on Unsplash

Written & edited by — Vivek Mittal

https://www.linkedin.com/in/vivekmittal06/

Additional reading

--

--