Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python State Pattern

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:

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:

  1. Context: Maintains an instance of a Concrete State object, which defines the current state
  2. State (State Interface): Defines an interface for encapsulating behavior associated with a specific state of the Context
  3. 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

)

:

       

print

(

"The door is already open"

)

       

return

self

   

   

def

close_doors

(

self

)

:

       

print

(

"Closing the door..."

)

       

return

DoorClosedState

(

)

   

   

def

move

(

self

)

:

       

print

(

"Error: the door is still open, cannot move"

)

       

return

self

   

   

def

stop

(

self

)

:

       

print

(

"The elevator has stopped"

)

       

return

self

class

DoorClosedState

(

ElevatorState

)

:

   

"""Closed-door state"""

   

   

def

open_doors

(

self

)

:

       

print

(

"Opening the door..."

)

       

return

DoorOpenState

(

)

   

   

def

close_doors

(

self

)

:

       

print

(

"The door is already closed"

)

       

return

self

   

   

def

move

(

self

)

:

       

print

(

"The elevator starts moving..."

)

       

return

MovingState

(

)

   

   

def

stop

(

self

)

:

       

print

(

"The elevator has stopped"

)

       

return

self

class

MovingState

(

ElevatorState

)

:

   

"""Moving state"""

   

   

def

open_doors

(

self

)

:

       

print

(

"Error: the elevator is moving, cannot open the door"

)

       

return

self

   

   

def

close_doors

(

self

)

:

       

print

(

"The door is already closed"

)

       

return

self

   

   

def

move

(

self

)

:

       

print

(

"The elevator is moving"

)

       

return

self

   

   

def

stop

(

self

)

:

       

print

(

"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

       

print

(

f

"State switched to: {state.class.name}"

)

   

   

def

open_doors

(

self

)

:

       

"""Open-door operation"""

       

print

(

"Executing open-door operation..."

)

       

self

.

set_state

(

self

._state.

open_doors

(

)

)

   

   

def

close_doors

(

self

)

:

       

"""Close-door operation"""

       

print

(

"Executing close-door operation..."

)

       

self

.

set_state

(

self

._state.

close_doors

(

)

)

   

   

def

move

(

self

)

:

       

"""Move operation"""

       

print

(

"Executing move operation..."

)

       

self

.

set_state

(

self

._state.

move

(

)

)

   

   

def

stop

(

self

)

:

       

"""Stop operation"""

       

print

(

"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

print

(

"=== 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

print

(

"\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

)

:

       

print

(

"The door is already open"

)

       

return

self

   

   

def

close_doors

(

self

)

:

       

print

(

"Closing the door..."

)

       

return

SharedDoorClosedState

(

)

   

   

def

move

(

self

)

:

       

print

(

"Error: the door is still open, cannot move"

)

       

return

self

   

   

def

stop

(

self

)

:

       

print

(

"The elevator has stopped"

)

       

return

self

class

SharedDoorClosedState

(

ElevatorState

,

metaclass

=

Singleton

)

:

   

"""Shared closed-door state (singleton)"""

   

   

def

open_doors

(

self

)

:

       

print

(

"Opening the door..."

)

       

return

SharedDoorOpenState

(

)

   

   

def

close_doors

(

self

)

:

       

print

(

"The door is already closed"

)

       

return

self

   

   

def

move

(

self

)

:

       

print

(

"The elevator starts moving..."

)

       

return

SharedMovingState

(

)

   

   

def

stop

(

self

)

:

       

print

(

"The elevator has stopped"

)

       

return

self

class

SharedMovingState

(

ElevatorState

,

metaclass

=

Singleton

)

:

   

"""Shared moving state (singleton)"""

   

   

def

open_doors

(

self

)

:

       

print

(

"Error: the elevator is moving, cannot open the door"

)

       

return

self

   

   

def

close_doors

(

self

)

:

       

print

(

"The door is already closed"

)

       

return

self

   

   

def

move

(

self

)

:

       

print

(

"The elevator is moving"

)

       

return

self

   

   

def

stop

(

self

)

:

       

print

(

"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

)

:

       

print

(

f

"Inserted {amount} yuan"

)

        machine.

balance

=

amount

       

return

HasMoneyState

(

)

   

   

def

select_product

(

self

,

machine

,

product

)

:

       

print

(

"Please insert a coin first"

)

       

return

self

   

   

def

dispense

(

self

,

machine

)

:

       

print

(

"Please insert a coin and select a product first"

)

       

return

self

   

   

def

refund

(

self

,

machine

)

:

       

print

(

"There is no amount to refund"

)

       

return

self

class

HasMoneyState

(

VendingMachineState

)

:

   

"""Coin-inserted state"""

   

   

def

insert_coin

(

self

,

machine

,

amount

)

:

       

print

(

f

"Insert another {amount} yuan"

)

        machine.

balance

=

amount

       

return

self

   

   

def

select_product

(

self

,

machine

,

product

)

:

       

if

product.

price

<=

machine.

balance

:

           

print

(

f

"Product selected: {product.name}"

)

            machine.

selected_product

=

product

           

return

ProductSelectedState

(

)

       

else

:

           

print

(

"Insufficient balance; please insert more coins or choose a cheaper product"

)

           

return

self

   

   

def

dispense

(

self

,

machine

)

:

       

print

(

"Please select a product first"

)

       

return

self

   

   

def

refund

(

self

,

machine

)

:

       

print

(

f

"Refunding {machine.balance} yuan"

)

        machine.

balance

=

0

       

return

WaitingState

(

)

class

ProductSelectedState

(

VendingMachineState

)

:

   

"""Product-selected state"""

   

   

def

insert_coin

(

self

,

machine

,

amount

)

:

       

print

(

"A product has been selected; cannot insert more coins"

)

       

return

self

   

   

def

select_product

(

self

,

machine

,

product

)

:

       

print

(

"A product has been selected; please complete the current transaction first"

)

       

return

self

   

   

def

dispense

(

self

,

machine

)

:

        product

=

machine.

selected_product

        change

=

machine.

balance

price

       

       

print

(

f

"Dispensing: {product.name}"

)

       

if

change

0

:

           

print

(

f

"Change: {change} yuan"

)

       

        machine.

balance

=

0

        machine.

selected_product

=

None

       

return

WaitingState

(

)

   

   

def

refund

(

self

,

machine

)

:

       

print

(

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

)

:

       

print

(

f

"Operation: insert {amount} yuan"

)

       

self

.

set_state

(

self

._state.

insert_coin

(

self

,

amount

)

)

   

   

def

select_product

(

self

,

product

)

:

       

print

(

f

"Operation: select product {product.name}"

)

       

self

.

set_state

(

self

._state.

select_product

(

self

,

product

)

)

   

   

def

dispense

(

self

)

:

       

print

(

"Operation: request dispensing"

)

       

self

.

set_state

(

self

._state.

dispense

(

self

)

)

   

   

def

refund

(

self

)

:

       

print

(

"Operation: request refund"

)

       

self

.

set_state

(

self

._state.

refund

(

self

)

)


Advantages and Disadvantages of the State Pattern

Advantages

  1. Single responsibility principle: Places code related to a specific state in a separate class
  2. Open-Closed Principle: New states can be introduced without modifying existing state classes or the Context
  3. Eliminate conditional statements: Eliminates huge conditional branches through polymorphic calls
  4. Explicit state transitions: Makes state transitions more explicit and reduces errors caused by them

Disadvantages

  1. Possible over-engineering: If there are few states or they rarely change, using the State Pattern may be overly complex
  2. Increased number of state classes: Each state requires a corresponding class, which can increase the number of classes
  3. 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:

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:

Exercise 3: Game Character States

Design a state system for a game character with the following states:


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: