What is a State Machine?
Any device that changes its state from one to another due to some actions are defined to be state machines. For example an ATM machine, traffic signal, remote control, the computer itself, etc. Most software applications also depend and operate based on the state. There are two types of state machines.
1. Finite state machine – A state machine holding a defined set of states and they work within that.
2. Infinite state machine – Here the states can be many and cannot be predefined.
Most common state machines are finite ones
Composition of a State Machine
The following things collectively make an effective finite state machine.
State:
A defined set of states. At any point of time the state machine will be in any one of the defined states. For example Red, Green and Yellow in a traffic signal system.
State Transition:
A state machine changing its state from one to another is called State Transition. Usually there will be a state transition table built that will contain the state sequences and also metadata saying which event will cause which state transition.
Triggers:
Triggers are the points that induce the state transition in a state machine.
Events or Actions:
Actions are performed by the state machines when a particular state is attained and exited. There will be Entry and Exit actions for each state.
Guard Condition:
This is the piece of component that validates the transition and ensures that no invalid state changes are carried out.
State Transition Table:
The turnstile state machine can be represented by a state transition table, showing for each state the new state and the output (action) resulting from each input
Current State | Input | Next State | Output |
---|---|---|---|
Locked | coin | Unlocked | Unlock turnstile so customer can push through |
push | Locked | None | |
Unlocked | coin | Unlocked | None |
push | Locked | When customer has pushed through, lock turnstile |
State machine 和 软件设计模式里面的 state pattern 是有区别的。
实现 State machine 并不一定需要用 State pattern, 模式。
但是用 state pattern 模式来实现状态机比较清晰和易于理解。
关于State machine . 这里有篇很好的文章:
https://docs.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/state-machine-workflows