Let an object change its behaviour when its internal state changes, by moving each state's behaviour into a separate class and delegating to the current one. From the outside it looks as if the object changed its class.
Some objects behave differently depending on what has already happened to them. A charger that is mid-session should not accept a new card. A faulted charger should not deliver power, whatever button gets pressed. The usual first version of this logic is a status field and a switch statement in every method. It works until the fifth state arrives.
The State pattern turns each state into its own object. The owner delegates every call to whichever state object is current, and that object decides what to do and which state comes next. In this guide you will follow one charging network from a tangle of conditionals to an explicit state machine, then see how to explain the trade-offs in an interview.
The problem
A situation where the obvious design starts to hurt.
VoltBay runs 420 public EV chargers across 60 car parks. A team of four writes the firmware that sits between the hardware and the central backend. Every charger is modelled by a ChargePoint class with a status string that can be available, authorized, charging or faulted.
The class has five event methods: tapCard, plugIn, unplug, fault and reset. Each one opens with a switch on status, so there are five switches of four branches each, twenty branches to keep consistent. When the product team asked for a reserved state, so drivers could book a bay from the app, the change touched every switch plus three helper methods that also checked status.
Then a field bug arrived: a charger in faulted state started delivering power because the plugIn switch had a fall-through that nobody had noticed. The rule "a faulted charger never powers on" was not written anywhere. It was implied by the absence of code across five methods. Reviewers could not see the state machine because it was smeared across the whole class.
The solution
What the pattern proposes.
Give each state its own class. Available, Authorized, Charging and Faulted all extend an abstract ChargerState that declares the five events. The base class supplies safe defaults: every event is rejected, except fault, which always cuts power and moves to Faulted. Each concrete state overrides only the events it actually handles.
ChargePoint becomes the context. It holds a reference to the current state object, exposes hardware operations such as startPower and stopPower, and forwards each event to the state with itself as an argument. The state does its work and, if needed, calls cp.setState(...) to install the next state.
Now the rule about faulted chargers lives in one place: Faulted does not override plugIn, so it inherits the rejection. Adding Reserved means writing one new class and changing the one or two states that can transition into it. Each state class reads like a row of the state transition table, which is exactly what a reviewer needs to see.
An everyday analogy
The same idea, outside software.
Think of a self-service car wash bay. When it is idle, the coin slot accepts money and the start button does nothing. Once you have paid, the start button begins the wash and the coin slot is closed. While the brushes are running, the only control that matters is the emergency stop. If a sensor trips, every control is dead until an attendant turns the key.
The buttons on the panel never change. What changes is the mode the machine is in, and each mode decides what the same buttons mean and which mode follows. The State pattern gives each of those modes its own object instead of wiring every button to a long list of checks.
Structure
The pieces and how they relate.
Participants
- ChargePoint (Context)
- Owns the current state object and the real resources, here the power relay. Exposes the public event methods and forwards each one to the current state, passing itself so the state can act on it and replace itself.
- ChargerState (State)
- Abstract base declaring every event the context can receive. Provides default behaviour: reject the event, except
fault, which cuts power and moves to Faulted from any state. - Available, Authorized, Charging, Faulted (Concrete States)
- Each implements the behaviour valid in that state and decides the next state. They may carry state-specific data, such as the card that authorised the session.
- OcppHandler (Client)
- Translates hardware signals and backend messages into calls on ChargePoint. It never inspects or changes the state directly.
Pseudocode
The solution to the scenario, language-neutral.
abstract class ChargerState
method tapCard(cp, cardId): return reject("tapCard")
method plugIn(cp): return reject("plugIn")
method unplug(cp): return reject("unplug")
method reset(cp): return reject("reset")
method fault(cp, code):
cp.stopPower()
cp.setState(new Faulted(code))
class Available extends ChargerState
method tapCard(cp, cardId):
cp.setState(new Authorized(cardId))
class Authorized extends ChargerState
field cardId
method tapCard(cp, otherCard):
if otherCard == cardId then cp.setState(new Available())
else reject: bay held for cardId
method plugIn(cp):
cp.startPower()
cp.setState(new Charging(cardId))
class Charging extends ChargerState
field cardId
method unplug(cp):
cp.stopPower()
cp.setState(new Available())
class Faulted extends ChargerState
field code
method reset(cp): cp.setState(new Available())
class ChargePoint
field state = new Available()
method setState(next): state = next
method tapCard(cardId): return state.tapCard(this, cardId)
method plugIn(): return state.plugIn(this)
// unplug, fault, reset forward the same wayThe code
The same solution in TypeScript, Python and PHP.
abstract class ChargerState {
abstract name(): string;
tapCard(_cp: ChargePoint, _cardId: string): string {
return this.reject("tapCard");
}
plugIn(_cp: ChargePoint): string {
return this.reject("plugIn");
}
unplug(_cp: ChargePoint): string {
return this.reject("unplug");
}
reset(_cp: ChargePoint): string {
return this.reject("reset");
}
fault(cp: ChargePoint, code: string): string {
cp.stopPower();
cp.setState(new Faulted(code));
return `fault ${code}: power cut`;
}
protected reject(action: string): string {
return `${action} ignored while ${this.name()}`;
}
}
class Available extends ChargerState {
name(): string {
return "available";
}
tapCard(cp: ChargePoint, cardId: string): string {
cp.setState(new Authorized(cardId));
return `card ${cardId} authorized, plug in to start`;
}
}
class Authorized extends ChargerState {
constructor(private readonly cardId: string) {
super();
}
name(): string {
return "authorized";
}
tapCard(cp: ChargePoint, cardId: string): string {
if (cardId === this.cardId) {
cp.setState(new Available());
return `authorization for ${cardId} cancelled`;
}
return `card ${cardId} rejected: bay held for ${this.cardId}`;
}
plugIn(cp: ChargePoint): string {
cp.startPower();
cp.setState(new Charging(this.cardId));
return `charging for card ${this.cardId}`;
}
}
class Charging extends ChargerState {
constructor(private readonly cardId: string) {
super();
}
name(): string {
return "charging";
}
unplug(cp: ChargePoint): string {
cp.stopPower();
cp.setState(new Available());
return `session for ${this.cardId} closed`;
}
}
class Faulted extends ChargerState {
constructor(private readonly code: string) {
super();
}
name(): string {
return "faulted";
}
reset(cp: ChargePoint): string {
cp.setState(new Available());
return `fault ${this.code} cleared`;
}
}
class ChargePoint {
private state: ChargerState = new Available();
powerOn = false;
constructor(readonly id: string) {}
setState(next: ChargerState): void {
this.state = next;
}
stateName(): string {
return this.state.name();
}
startPower(): void {
this.powerOn = true;
}
stopPower(): void {
this.powerOn = false;
}
tapCard(cardId: string): string {
return this.state.tapCard(this, cardId);
}
plugIn(): string {
return this.state.plugIn(this);
}
unplug(): string {
return this.state.unplug(this);
}
fault(code: string): string {
return this.state.fault(this, code);
}
reset(): string {
return this.state.reset(this);
}
}
const cp = new ChargePoint("VB-017");
const steps: Array<() => string> = [
() => cp.plugIn(),
() => cp.tapCard("C-881"),
() => cp.tapCard("C-204"),
() => cp.plugIn(),
() => cp.fault("GROUND_FAULT"),
() => cp.unplug(),
() => cp.reset(),
];
for (const step of steps) {
const result = step();
console.log(`${result} -> ${cp.stateName()} (power ${cp.powerOn ? "on" : "off"})`);
}class ChargerState:
def name(self) -> str:
raise NotImplementedError
def tap_card(self, cp: "ChargePoint", card_id: str) -> str:
return self._reject("tapCard")
def plug_in(self, cp: "ChargePoint") -> str:
return self._reject("plugIn")
def unplug(self, cp: "ChargePoint") -> str:
return self._reject("unplug")
def reset(self, cp: "ChargePoint") -> str:
return self._reject("reset")
def fault(self, cp: "ChargePoint", code: str) -> str:
cp.stop_power()
cp.set_state(Faulted(code))
return f"fault {code}: power cut"
def _reject(self, action: str) -> str:
return f"{action} ignored while {self.name()}"
class Available(ChargerState):
def name(self) -> str:
return "available"
def tap_card(self, cp: "ChargePoint", card_id: str) -> str:
cp.set_state(Authorized(card_id))
return f"card {card_id} authorized, plug in to start"
class Authorized(ChargerState):
def __init__(self, card_id: str) -> None:
self._card_id = card_id
def name(self) -> str:
return "authorized"
def tap_card(self, cp: "ChargePoint", card_id: str) -> str:
if card_id == self._card_id:
cp.set_state(Available())
return f"authorization for {card_id} cancelled"
return f"card {card_id} rejected: bay held for {self._card_id}"
def plug_in(self, cp: "ChargePoint") -> str:
cp.start_power()
cp.set_state(Charging(self._card_id))
return f"charging for card {self._card_id}"
class Charging(ChargerState):
def __init__(self, card_id: str) -> None:
self._card_id = card_id
def name(self) -> str:
return "charging"
def unplug(self, cp: "ChargePoint") -> str:
cp.stop_power()
cp.set_state(Available())
return f"session for {self._card_id} closed"
class Faulted(ChargerState):
def __init__(self, code: str) -> None:
self._code = code
def name(self) -> str:
return "faulted"
def reset(self, cp: "ChargePoint") -> str:
cp.set_state(Available())
return f"fault {self._code} cleared"
class ChargePoint:
def __init__(self, charger_id: str) -> None:
self.id = charger_id
self.power_on = False
self._state: ChargerState = Available()
def set_state(self, next_state: ChargerState) -> None:
self._state = next_state
def state_name(self) -> str:
return self._state.name()
def start_power(self) -> None:
self.power_on = True
def stop_power(self) -> None:
self.power_on = False
def tap_card(self, card_id: str) -> str:
return self._state.tap_card(self, card_id)
def plug_in(self) -> str:
return self._state.plug_in(self)
def unplug(self) -> str:
return self._state.unplug(self)
def fault(self, code: str) -> str:
return self._state.fault(self, code)
def reset(self) -> str:
return self._state.reset(self)
if __name__ == "__main__":
cp = ChargePoint("VB-017")
steps = [
lambda: cp.plug_in(),
lambda: cp.tap_card("C-881"),
lambda: cp.tap_card("C-204"),
lambda: cp.plug_in(),
lambda: cp.fault("GROUND_FAULT"),
lambda: cp.unplug(),
lambda: cp.reset(),
]
for step in steps:
result = step()
power = "on" if cp.power_on else "off"
print(f"{result} -> {cp.state_name()} (power {power})")<?php
declare(strict_types=1);
abstract class ChargerState
{
abstract public function name(): string;
public function tapCard(ChargePoint $cp, string $cardId): string
{
return $this->reject('tapCard');
}
public function plugIn(ChargePoint $cp): string
{
return $this->reject('plugIn');
}
public function unplug(ChargePoint $cp): string
{
return $this->reject('unplug');
}
public function reset(ChargePoint $cp): string
{
return $this->reject('reset');
}
public function fault(ChargePoint $cp, string $code): string
{
$cp->stopPower();
$cp->setState(new Faulted($code));
return 'fault ' . $code . ': power cut';
}
protected function reject(string $action): string
{
return $action . ' ignored while ' . $this->name();
}
}
final class Available extends ChargerState
{
public function name(): string
{
return 'available';
}
public function tapCard(ChargePoint $cp, string $cardId): string
{
$cp->setState(new Authorized($cardId));
return 'card ' . $cardId . ' authorized, plug in to start';
}
}
final class Authorized extends ChargerState
{
public function __construct(private readonly string $cardId)
{
}
public function name(): string
{
return 'authorized';
}
public function tapCard(ChargePoint $cp, string $cardId): string
{
if ($cardId === $this->cardId) {
$cp->setState(new Available());
return 'authorization for ' . $cardId . ' cancelled';
}
return 'card ' . $cardId . ' rejected: bay held for ' . $this->cardId;
}
public function plugIn(ChargePoint $cp): string
{
$cp->startPower();
$cp->setState(new Charging($this->cardId));
return 'charging for card ' . $this->cardId;
}
}
final class Charging extends ChargerState
{
public function __construct(private readonly string $cardId)
{
}
public function name(): string
{
return 'charging';
}
public function unplug(ChargePoint $cp): string
{
$cp->stopPower();
$cp->setState(new Available());
return 'session for ' . $this->cardId . ' closed';
}
}
final class Faulted extends ChargerState
{
public function __construct(private readonly string $code)
{
}
public function name(): string
{
return 'faulted';
}
public function reset(ChargePoint $cp): string
{
$cp->setState(new Available());
return 'fault ' . $this->code . ' cleared';
}
}
final class ChargePoint
{
private ChargerState $state;
public bool $powerOn = false;
public function __construct(public readonly string $id)
{
$this->state = new Available();
}
public function setState(ChargerState $next): void
{
$this->state = $next;
}
public function stateName(): string
{
return $this->state->name();
}
public function startPower(): void
{
$this->powerOn = true;
}
public function stopPower(): void
{
$this->powerOn = false;
}
public function tapCard(string $cardId): string
{
return $this->state->tapCard($this, $cardId);
}
public function plugIn(): string
{
return $this->state->plugIn($this);
}
public function unplug(): string
{
return $this->state->unplug($this);
}
public function fault(string $code): string
{
return $this->state->fault($this, $code);
}
public function reset(): string
{
return $this->state->reset($this);
}
}
$cp = new ChargePoint('VB-017');
$steps = [
fn() => $cp->plugIn(),
fn() => $cp->tapCard('C-881'),
fn() => $cp->tapCard('C-204'),
fn() => $cp->plugIn(),
fn() => $cp->fault('GROUND_FAULT'),
fn() => $cp->unplug(),
fn() => $cp->reset(),
];
foreach ($steps as $step) {
$result = $step();
$power = $cp->powerOn ? 'on' : 'off';
echo $result . ' -> ' . $cp->stateName() . ' (power ' . $power . ')' . PHP_EOL;
}When to use it
Situations where it pays off.
An object's behaviour depends on its state, and the same few conditionals on a status field appear in many methods.
Each switch is a slice of the state machine. Moving the branches into state classes collects every rule for one state in one place, so adding or changing a state stops being shotgun surgery.
Some events are only legal in certain states and an illegal one must be harmless, such as powering on a faulted charger.
A base class that rejects by default makes forbidden transitions the safe outcome. A state must opt in to an event by overriding it, rather than every method having to remember to opt out.
States carry their own data, like the card that authorised a session or the fault code that stopped it.
State objects can hold fields that only make sense while that state is active. You avoid nullable fields on the context that are valid only some of the time.
Not when there are two states and one or two methods care about them.
A boolean and an if statement are easier to read than an abstract class and two subclasses. Reach for the pattern when the number of states or state-dependent methods starts to grow.
How to implement it
Steps to introduce it in existing code.
List every state and every event, then write the transition table: for each pair, what happens and which state comes next. This table is your specification and your test plan.
Declare an abstract state class or interface with one method per event. Each method takes the context as a parameter so the state can call back into it.
Put safe defaults in the base class, usually rejecting the event. Put transitions that apply to every state there too, like
faultmoving to Faulted.Create one concrete class per state and override only the events that do something in that state. Move any data that belongs to a single state into that class as a field.
Change the context to hold a reference to the current state, add a
setStatemethod, and make each public event method forward to the state.Delete the old status field and switches. If other code needs to read the state for display or persistence, expose a
name()on the state rather than leaking the object.Test each state in isolation by constructing it, calling events on a context, and asserting on the resulting state and side effects.
Pros and cons
What you gain and what you pay.
Pros
- All behaviour for one state lives in one class, so the state machine is visible in the code rather than implied by scattered branches.
- Adding a state means adding a class and touching only the states that transition into it, which keeps changes local (Open/Closed in practice).
- Illegal events fall through to a shared default, which makes the safe behaviour automatic instead of something each method must remember.
- State-specific data lives on the state object, so the context has no fields that are meaningful only part of the time.
- Each state can be unit-tested on its own with a small fake or real context.
Cons
- More classes. For a machine with two or three states and simple rules, the pattern adds structure that a single switch would not need.
- Transitions are spread across state classes, so you cannot see the whole graph in one file. Keep the transition table in documentation or tests.
- States that call back into the context create a two-way dependency, and the context often has to expose methods like
startPowerthat only states should use. - Creating a new state object on every transition allocates; if states have no data, share single instances instead.
Relations with other guides
Patterns it's often confused or combined with.
- Strategy: swap the rule without touching who uses it
Same structure, different intent. A Strategy is chosen by the client and usually does not know other strategies exist. A State is swapped by the states themselves as events arrive, and each one knows its successors.
- Repeated Switches: the same type-code switch scattered across a codebase
The same switch on a status field in several methods is the classic signal that a State pattern is waiting to be extracted.
- Replace Conditional with Polymorphism: One Class per Case
This refactoring is the mechanical route to State: each branch of the status switch becomes an override in a state subclass.
- Singleton: One Shared Instance, and Why You Usually Want DI Instead
States without fields, like Available here, can be shared single instances so transitions do not allocate. States with data, like Authorized, still need fresh objects.
- Circuit breaker: fail fast when a dependency is down
A circuit breaker is a state machine with closed, open and half-open states, and is often implemented with exactly this pattern.
- Memento Pattern: Save and Restore State Without Exposing It
When you need to persist or roll back a state machine, a memento can capture the current state name and its data without exposing the state objects.
Common questions
Short answers to the usual doubts.
What is the difference between State and Strategy?
The class diagrams are nearly identical: a context delegating to an interchangeable object. The difference is who swaps the object and why. With Strategy, the client picks an algorithm and it usually stays put; strategies do not know about each other. With State, the state objects replace themselves in response to events, so each state knows which states can follow it. If the swap is driven by the object's own history, you are looking at State.
Should the context or the state classes decide the next state?
Either works. Letting states call setState, as in the VoltBay code, keeps each transition next to the behaviour that causes it and makes adding states local. Centralising transitions in the context or a table gives you one place to read the whole graph, at the cost of the context knowing every state. In an interview, name both options and say which trade-off fits the problem.
When is a transition table better than the State pattern?
When states differ only in which transitions are allowed and carry little behaviour, a table mapping (state, event) to next state is shorter and easy to load from configuration. The State pattern earns its keep when each state has real logic, side effects such as switching power, or its own data. Many systems combine them: a table for legality, state classes for behaviour.
How do you persist a state machine to a database?
Store the state's name plus any state-specific data, for example authorized and the card id. On load, a small factory maps the name back to a state class and constructs it with the saved data. Do not serialise the state objects directly; the name is a stable contract, the class layout is not.
Do I need a new state object on every transition?
Only for states that hold data. Stateless states such as Available can be single shared instances, which avoids allocation and makes identity comparisons cheap. States like Authorized, which remember a card id, must be created per transition or the data would leak between chargers.