Python State Pattern
The core idea of the State Pattern is to encapsulate an object's states into separate classes and delegate the object's behavior to the current state object. When the object's state changes, it switches to a different state object, thereby changing its behavior.
Why Do We Need the State Pattern?
Without the State Pattern, we typically use a large number of if-else or switch-case statements in a class to handle behavior under different states. This approach has several problems:
- Bloated code: As the number of states grows, conditional statements become increasingly complex
- Hard to maintain: Modifying the behavior of one state may affect other states
- Violates the Open-Closed Principle: Adding a new state requires modifying existing code
The State Pattern solves these problems by encapsulating each state into a separate class.
Structure of the State Pattern
Main Roles
The State Pattern contains three core roles:
- Context: Maintains an instance of a Concrete State object, which defines the current state
- State (State Interface): Defines an interface for encapsulating behavior associated with a specific state of the Context
- ConcreteState (Concrete State): Implements the State interface; each concrete state class implements a behavior associated with a state of the Context
UML Class Diagram

Implementation of the State Pattern
Basic Implementation Steps
Let's understand the implementation of the State Pattern through a simple example. Suppose we have an elevator system with different states: open, closed, moving, and stopped.
Step 1: Define the State Interface
Example
from
abc
import
ABC
,
abstractmethod
class
ElevatorState
(
ABC
)
:
"""Elevator state interface"""
@
abstractmethod
def
open_doors
(
self
)
:
"""Open-door operation"""
pass
@
abstractmethod
def
close_doors
(
self
)
:
"""Close-door operation"""
pass
@
abstractmethod
def
move
(
self
)
:
"""Move operation"""
pass
@
abstractmethod
def
stop
(
self
)
:
"""Stop operation"""
pass
Step 2: Implement Concrete State Classes
Example
class
DoorOpenState
(
ElevatorState
)
:
"""Open-door state"""
def
open_doors
(
self
)
:
(
"The door is already open"
)
return
self
def
close_doors
(
self
)
:
(
"Closing the door..."
)
return
DoorClosedState
(
)
def
move
(
self
)
:
(
"Error: the door is still open, cannot move"
)
return
self
def
stop
(
self
)
:
(
"The elevator has stopped"
)
return
self
class
DoorClosedState
(
ElevatorState
)
:
"""Closed-door state"""
def
open_doors
(
self
)
:
(
"Opening the door..."
)
return
DoorOpenState
(
)
def
close_doors
(
self
)
:
(
"The door is already closed"
)
return
self
def
move
(
self
)
:
(
"The elevator starts moving..."
)
return
MovingState
(
)
def
stop
(
self
)
:
(
"The elevator has stopped"
)
return
self
class
MovingState
(
ElevatorState
)
:
"""Moving state"""
def
open_doors
(
self
)
:
(
"Error: the elevator is moving, cannot open the door"
)
return
self
def
close_doors
(
self
)
:
(
"The door is already closed"
)
return
self
def
move
(
self
)
:
(
"The elevator is moving"
)
return
self
def
stop
(
self
)
:
(
"The elevator is stopping..."
)
return
DoorClosedState
(
)
Step 3: Create the Context Class
Example
class
Elevator:
"""Elevator context class"""
def
init
(
self
)
:
Initial state is the door-closed state
self
._state
=
DoorClosedState
(
)
@
property
def
state
(
self
)
:
"""Get the current state"""
return
self
._state
def
set_state
(
self
,
state
)
:
"""Set a new state"""
self
._state
=
state
(
f
"State switched to: {state.class.name}"
)
def
open_doors
(
self
)
:
"""Open-door operation"""
(
"Executing open-door operation..."
)
self
.
set_state
(
self
._state.
open_doors
(
)
)
def
close_doors
(
self
)
:
"""Close-door operation"""
(
"Executing close-door operation..."
)
self
.
set_state
(
self
._state.
close_doors
(
)
)
def
move
(
self
)
:
"""Move operation"""
(
"Executing move operation..."
)
self
.
set_state
(
self
._state.
move
(
)
)
def
stop
(
self
)
:
"""Stop operation"""
(
"Executing stop operation..."
)
self
.
set_state
(
self
._state.
stop
(
)
)
Step 4: Use the State Pattern
Example
Create an elevator instance
elevator
=
Elevator
(
)
Test state transitions
(
"=== Elevator State Transition Test ==="
)
elevator.
open_doors
(
)
Switch from the closed-door state to the open-door state
elevator.
close_doors
(
)
Switch back from the open-door state to the closed-door state
elevator.
move
(
)
Switch from the closed-door state to the moving state
elevator.
stop
(
)
Switch back from the moving state to the closed-door state
(
"\n=== Test Illegal Operations ==="
)
elevator.
open_doors
(
)
Open the door normally
elevator.
move
(
)
Try to move while in the open-door state (should report an error)
Run Results
=== 电梯状态转换测试 ===
执行开门操作...
正在开门...
状态已切换为: DoorOpenState
执行关门操作...
正在关门...
状态已切换为: DoorClosedState
执行移动操作...
电梯开始移动...
状态已切换为: MovingState
执行停止操作...
电梯停止中...
状态已切换为: DoorClosedState
=== 测试非法操作 ===
执行开门操作...
正在开门...
状态已切换为: DoorOpenState
执行移动操作...
错误:门还开着,不能移动
状态已切换为: DoorOpenState
Advanced Applications of the State Pattern
State Pattern with Shared States
In some cases, multiple contexts may need to share the same state object. We can achieve state sharing through the Singleton Pattern.
Example
class
Singleton
(
type
)
:
"""Singleton metaclass"""
_instances
=
{
}
def
call
(
cls
,
*args
,
**kwargs
)
:
if
cls
not
in
cls._instances:
cls._instances
[
cls
]
=
super
(
)
.
call
(
*args
,
**kwargs
)
return
cls._instances
[
cls
]
class
SharedDoorOpenState
(
ElevatorState
,
metaclass
=
Singleton
)
:
"""Shared open-door state (singleton)"""
def
open_doors
(
self
)
:
(
"The door is already open"
)
return
self
def
close_doors
(
self
)
:
(
"Closing the door..."
)
return
SharedDoorClosedState
(
)
def
move
(
self
)
:
(
"Error: the door is still open, cannot move"
)
return
self
def
stop
(
self
)
:
(
"The elevator has stopped"
)
return
self
class
SharedDoorClosedState
(
ElevatorState
,
metaclass
=
Singleton
)
:
"""Shared closed-door state (singleton)"""
def
open_doors
(
self
)
:
(
"Opening the door..."
)
return
SharedDoorOpenState
(
)
def
close_doors
(
self
)
:
(
"The door is already closed"
)
return
self
def
move
(
self
)
:
(
"The elevator starts moving..."
)
return
SharedMovingState
(
)
def
stop
(
self
)
:
(
"The elevator has stopped"
)
return
self
class
SharedMovingState
(
ElevatorState
,
metaclass
=
Singleton
)
:
"""Shared moving state (singleton)"""
def
open_doors
(
self
)
:
(
"Error: the elevator is moving, cannot open the door"
)
return
self
def
close_doors
(
self
)
:
(
"The door is already closed"
)
return
self
def
move
(
self
)
:
(
"The elevator is moving"
)
return
self
def
stop
(
self
)
:
(
"The elevator is stopping..."
)
return
SharedDoorClosedState
(
)
State Pattern and State Machine
The State Pattern is often used together with a state machine. Here is a more complex state machine example:
Example
class
VendingMachineState
(
ABC
)
:
"""Vending machine state interface"""
@
abstractmethod
def
insert_coin
(
self
,
machine
,
amount
)
:
"""Insert coin"""
pass
@
abstractmethod
def
select_product
(
self
,
machine
,
product
)
:
"""Select product"""
pass
@
abstractmethod
def
dispense
(
self
,
machine
)
:
"""Dispense product"""
pass
@
abstractmethod
def
refund
(
self
,
machine
)
:
"""Refund"""
pass
class
WaitingState
(
VendingMachineState
)
:
"""Waiting-for-coin state"""
def
insert_coin
(
self
,
machine
,
amount
)
:
(
f
"Inserted {amount} yuan"
)
machine.
balance
=
amount
return
HasMoneyState
(
)
def
select_product
(
self
,
machine
,
product
)
:
(
"Please insert a coin first"
)
return
self
def
dispense
(
self
,
machine
)
:
(
"Please insert a coin and select a product first"
)
return
self
def
refund
(
self
,
machine
)
:
(
"There is no amount to refund"
)
return
self
class
HasMoneyState
(
VendingMachineState
)
:
"""Coin-inserted state"""
def
insert_coin
(
self
,
machine
,
amount
)
:
(
f
"Insert another {amount} yuan"
)
machine.
balance
=
amount
return
self
def
select_product
(
self
,
machine
,
product
)
:
if
product.
price
<=
machine.
balance
:
(
f
"Product selected: {product.name}"
)
machine.
selected_product
=
product
return
ProductSelectedState
(
)
else
:
(
"Insufficient balance; please insert more coins or choose a cheaper product"
)
return
self
def
dispense
(
self
,
machine
)
:
(
"Please select a product first"
)
return
self
def
refund
(
self
,
machine
)
:
(
f
"Refunding {machine.balance} yuan"
)
machine.
balance
=
0
return
WaitingState
(
)
class
ProductSelectedState
(
VendingMachineState
)
:
"""Product-selected state"""
def
insert_coin
(
self
,
machine
,
amount
)
:
(
"A product has been selected; cannot insert more coins"
)
return
self
def
select_product
(
self
,
machine
,
product
)
:
(
"A product has been selected; please complete the current transaction first"
)
return
self
def
dispense
(
self
,
machine
)
:
product
=
machine.
selected_product
change
=
machine.
balance
- product.
price
(
f
"Dispensing: {product.name}"
)
if
change
0
:
(
f
"Change: {change} yuan"
)
machine.
balance
=
0
machine.
selected_product
=
None
return
WaitingState
(
)
def
refund
(
self
,
machine
)
:
(
f
"Refunding {machine.balance} yuan"
)
machine.
balance
=
0
machine.
selected_product
=
None
return
WaitingState
(
)
class
Product:
"""Product class"""
def
init
(
self
,
name
,
price
)
:
self
.
name
=
name
self
.
price
=
price
class
VendingMachine:
"""Vending machine"""
def
init
(
self
)
:
self
._state
=
WaitingState
(
)
self
.
balance
=
0
self
.
selected_product
=
None
def
set_state
(
self
,
state
)
:
self
._state
=
state
def
insert_coin
(
self
,
amount
)
:
(
f
"Operation: insert {amount} yuan"
)
self
.
set_state
(
self
._state.
insert_coin
(
self
,
amount
)
)
def
select_product
(
self
,
product
)
:
(
f
"Operation: select product {product.name}"
)
self
.
set_state
(
self
._state.
select_product
(
self
,
product
)
)
def
dispense
(
self
)
:
(
"Operation: request dispensing"
)
self
.
set_state
(
self
._state.
dispense
(
self
)
)
def
refund
(
self
)
:
(
"Operation: request refund"
)
self
.
set_state
(
self
._state.
refund
(
self
)
)
Advantages and Disadvantages of the State Pattern
Advantages
- Single responsibility principle: Places code related to a specific state in a separate class
- Open-Closed Principle: New states can be introduced without modifying existing state classes or the Context
- Eliminate conditional statements: Eliminates huge conditional branches through polymorphic calls
- Explicit state transitions: Makes state transitions more explicit and reduces errors caused by them
Disadvantages
- Possible over-engineering: If there are few states or they rarely change, using the State Pattern may be overly complex
- Increased number of state classes: Each state requires a corresponding class, which can increase the number of classes
- Coupling between Context and states: The Context needs to know all concrete state classes in order to perform state transitions
Practical Exercise
Exercise 1: Improve the Elevator System
Try adding the following features to the elevator system:
- Add an "Under Maintenance" state in which all operations are disabled
- Add floor selection, allowing floor selection only in the stopped state
- Implement automatic state transition upon arriving at a floor
Exercise 2: Implement a Traffic Light System
Use the State Pattern to implement a traffic light system with three states - red, green, and yellow - with the following transition rules:
- Red light → Green light (after 30 seconds)
- Green light → Yellow light (after 25 seconds)
- Yellow light → Red light (after 5 seconds)
Exercise 3: Game Character States
Design a state system for a game character with the following states:
- Normal state: can move and attack
- Poisoned state: continuously loses health, movement speed halved
- Stunned state: cannot move or attack
- Invincible state: takes no damage
Summary
The State Pattern is a powerful design pattern, especially suitable for scenarios where an object's behavior depends on its state, with many states and complex transitions. By encapsulating each state into a separate class, the State Pattern makes code clearer, easier to maintain, and easier to extend.
Key Points:
- The State Pattern eliminates conditional checks by encapsulating states as objects
- The Context delegates state-related behavior to the current state object
- State transitions can be triggered by the Context or by the state objects themselves
- Using the State Pattern appropriately can greatly improve code maintainability