Top 10 State Machine Design Patterns
Are you tired of writing spaghetti code that's hard to maintain and debug? Do you want to improve the reliability and scalability of your software? If so, you should consider using state machines in your design.
State machines are a powerful tool for modeling complex systems that have a finite number of states and transitions between them. They can help you write code that's easier to understand, test, and modify. In this article, we'll explore the top 10 state machine design patterns that you can use in your projects.
1. Simple State Machine
The simplest state machine consists of a set of states and transitions between them. Each state represents a condition or a mode of operation, and each transition represents a change from one state to another. For example, a traffic light can be modeled as a state machine with three states: red, yellow, and green.
stateDiagram-v2
[*] --> Red
Red --> Yellow
Yellow --> Green
Green --> Yellow
Yellow --> Red
In this diagram, the state machine starts in the initial state [*]
and transitions to the Red
state. From there, it can transition to the Yellow
state, and then to the Green
state. The Green
state can transition back to the Yellow
state, and the Yellow
state can transition back to the Red
state.
2. Hierarchical State Machine
A hierarchical state machine is a state machine that contains other state machines as substates. This allows you to model complex systems with multiple levels of abstraction. For example, a vending machine can be modeled as a hierarchical state machine with two levels: the outer level represents the overall state of the machine, while the inner level represents the state of each individual component.
stateDiagram-v2
[*] --> Idle
Idle --> Ready
Ready --> Dispensing
Dispensing --> Dispensed
Dispensing --> Failed
Ready --> Maintenance
Maintenance --> Idle
state Dispensing {
[*] --> Dispensing
Dispensing --> Dispensed
Dispensing --> Failed
}
In this diagram, the outer level of the state machine has four states: Idle
, Ready
, Dispensing
, and Maintenance
. The Dispensing
state is a substate of the Ready
state, and has two possible transitions: to the Dispensed
state or to the Failed
state.
3. Concurrent State Machine
A concurrent state machine is a state machine that contains multiple substates that can be active at the same time. This allows you to model systems that have multiple independent components that can operate in parallel. For example, a robot that can move and manipulate objects at the same time can be modeled as a concurrent state machine.
stateDiagram-v2
[*] --> Active
state Moving {
[*] --> Forward
Forward --> Backward
Backward --> Forward
}
state Manipulating {
[*] --> Grasping
Grasping --> Releasing
Releasing --> Grasping
}
In this diagram, the state machine has two substates: Moving
and Manipulating
. Both substates can be active at the same time, allowing the robot to move and manipulate objects simultaneously.
4. Mealy State Machine
A Mealy state machine is a state machine that produces outputs based on both the current state and the inputs. This allows you to model systems that have complex behavior that depends on both internal and external factors. For example, a thermostat that adjusts the temperature based on the current temperature and the desired temperature can be modeled as a Mealy state machine.
stateDiagram-v2
[*] --> Off
Off --> On: Heat
On --> Off: Cool
On --> On: Heat
On --> On: Cool
state On {
[*] --> Heating: Heat
[*] --> Cooling: Cool
state Heating {
[*] --> Normal
Normal --> Overheating: Temperature > Setpoint
Overheating --> Normal: Temperature < Setpoint - Hysteresis
}
state Cooling {
[*] --> Normal
Normal --> Undercooling: Temperature < Setpoint
Undercooling --> Normal: Temperature > Setpoint + Hysteresis
}
}
In this diagram, the state machine has two inputs: Heat
and Cool
. The output is the state of the thermostat: Off
or On
. When the thermostat is on, it can be in one of two substates: Heating
or Cooling
. The behavior of each substate depends on the current temperature and the desired temperature.
5. Moore State Machine
A Moore state machine is a state machine that produces outputs based only on the current state. This allows you to model systems that have simple behavior that depends only on internal factors. For example, a traffic light that changes color based on a fixed schedule can be modeled as a Moore state machine.
stateDiagram-v2
[*] --> Red
Red --> Green: 30s
Green --> Yellow: 5s
Yellow --> Red: 2s
In this diagram, the state machine has no inputs. The output is the color of the traffic light: Red
, Green
, or Yellow
. The behavior of the state machine is determined by a fixed schedule: the light stays red for 30 seconds, then turns green for 30 seconds, then turns yellow for 5 seconds, and finally turns red again.
6. Guarded State Machine
A guarded state machine is a state machine that has conditions associated with each transition. This allows you to model systems that have complex behavior that depends on multiple factors. For example, a door that can be locked or unlocked depending on the current state of a security system can be modeled as a guarded state machine.
stateDiagram-v2
[*] --> Closed
Closed --> Open: Unlock && AlarmOff
Open --> Closed: Lock || AlarmOn
In this diagram, the state machine has two inputs: Unlock
and Lock
, and two conditions: AlarmOff
and AlarmOn
. The output is the state of the door: Closed
or Open
. The behavior of the state machine depends on the current state of the security system: the door can be opened only if it's unlocked and the alarm is off, and can be closed only if it's locked or the alarm is on.
7. History State Machine
A history state machine is a state machine that remembers the last active substate. This allows you to model systems that have complex behavior that depends on the previous state. For example, a media player that resumes playback from the last position can be modeled as a history state machine.
stateDiagram-v2
[*] --> Stopped
Stopped --> Playing: Play
Playing --> Paused: Pause
Paused --> Playing: Play
Paused --> Stopped: Stop
Stopped --> LastPlayed: Resume
state Playing {
[*] --> Normal
Normal --> EndOfMedia: EndOfMedia
}
state Paused {
[*] --> Normal
}
state LastPlayed {
[*] --> Normal
}
In this diagram, the state machine has four substates: Stopped
, Playing
, Paused
, and LastPlayed
. The LastPlayed
state is a history state that remembers the last active substate. When the user resumes playback, the state machine transitions to the LastPlayed
state, which in turn transitions to the last active substate.
8. Orthogonal State Machine
An orthogonal state machine is a state machine that has multiple independent substate machines that can operate in parallel. This allows you to model systems that have multiple independent components that can operate in parallel. For example, a car that can drive and play music at the same time can be modeled as an orthogonal state machine.
stateDiagram-v2
[*] --> Driving
Driving --> Parking: Park
Driving --> Stopped: Stop
Driving --> Playing: Play
state Playing {
[*] --> Normal
Normal --> EndOfMedia: EndOfMedia
}
state Stopped {
[*] --> Normal
}
state Parking {
[*] --> Normal
}
In this diagram, the state machine has three independent substate machines: Driving
, Playing
, and Stopped
. The Driving
substate machine can transition to the Parking
substate machine, the Stopped
substate machine, or the Playing
substate machine.
9. Moore-Mealy State Machine
A Moore-Mealy state machine is a state machine that produces outputs based on both the current state and the inputs, and also has outputs that depend only on the current state. This allows you to model systems that have complex behavior that depends on both internal and external factors, as well as simple behavior that depends only on internal factors. For example, a washing machine that adjusts the cycle based on the current load and also displays the current status can be modeled as a Moore-Mealy state machine.
stateDiagram-v2
[*] --> Idle
Idle --> Fill: Start
Fill --> Wash: WaterLevelReached
Wash --> Drain: WashCycleComplete
Drain --> Rinse: DrainComplete
Rinse --> Drain: RinseCycleComplete
Drain --> Spin: RinseComplete
Spin --> Idle: SpinCycleComplete
[*] --> DisplayIdle
Fill --> DisplayFilling: Display
Wash --> DisplayWashing: Display
Drain --> DisplayDraining: Display
Rinse --> DisplayRinsing: Display
Spin --> DisplaySpinning: Display
state DisplayIdle {
[*] --> Idle
}
state DisplayFilling {
[*] --> Fill
}
state DisplayWashing {
[*] --> Wash
}
state DisplayDraining {
[*] --> Drain
}
state DisplayRinsing {
[*] --> Rinse
}
state DisplaySpinning {
[*] --> Spin
}
In this diagram, the state machine has two inputs: Start
and Display
. The output is the state of the washing machine: Idle
, Fill
, Wash
, Drain
, Rinse
, or Spin
. The behavior of the state machine depends on the current load and the current cycle: the machine fills with water, washes the clothes, drains the water, rinses the clothes, and spins the clothes. The state machine also has a display that shows the current status of the machine.
10. Extended State Machine
An extended state machine is a state machine that has additional variables that can be used to store and manipulate data. This allows you to model systems that have complex behavior that depends on internal and external factors that change over time. For example, a thermostat that adjusts the temperature based on the current temperature, the desired temperature, and the time of day can be modeled as an extended state machine.
stateDiagram-v2
[*] --> Off
Off --> On: Heat
On --> Off: Cool
On --> On: Heat
On --> On: Cool
state On {
[*] --> Heating: Heat
[*] --> Cooling: Cool
state Heating {
[*] --> Normal
Normal --> Overheating: Temperature > Setpoint
Overheating --> Normal: Temperature < Setpoint - Hysteresis
}
state Cooling {
[*] --> Normal
Normal --> Undercooling: Temperature < Setpoint
Undercooling --> Normal: Temperature > Setpoint + Hysteresis
}
state TimeOfDay {
[*] --> Day
Day --> Night: Time > Sunset
Night --> Day: Time < Sunrise
}
}
In this diagram, the state machine has three inputs: Heat
, Cool
, and Time
. The output is the state of the thermostat: Off
or On
. The behavior of each substate depends on the current temperature, the desired temperature, and the time of day: the thermostat heats or cools the room depending on the temperature and the desired temperature, and also adjusts the behavior based on the time of day.
Conclusion
State machines are a powerful tool for modeling complex systems that have a finite number of states and transitions between them. They can help you write code that's easier to understand, test, and modify. In this article, we've explored the top 10 state machine design patterns that you can use in your projects. Whether you're building a simple traffic light or a complex thermostat, state machines can help you write better code.
Editor Recommended Sites
AI and Tech NewsBest Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
Data Lineage: Cloud governance lineage and metadata catalog tooling for business and enterprise
Multi Cloud Business: Multicloud tutorials and learning for deploying terraform, kubernetes across cloud, and orchestrating
Realtime Data: Realtime data for streaming and processing
Customer 360 - Entity resolution and centralized customer view & Record linkage unification of customer master: Unify all data into a 360 view of the customer. Engineering techniques and best practice. Implementation for a cookieless world
Run Kubernetes: Kubernetes multicloud deployment for stateful and stateless data, and LLMs