当前位置:网站首页>Finite State Machine FSM
Finite State Machine FSM
2022-07-03 13:00:00 【Programmer spicy hot】
About the state machine , I wrote before. use Go Implement a state machine , It just talks about how to control the flow of state , Theoretically, it cannot be regarded as a complete state machine .
The process of a complete state machine is as follows : In a event( event ) after , According to the current existing state (cur-state), The decision to carry out “ action ”(action), And set the next status number (transition).
among :
event (Event) It means occupying a certain position in time and space , And those things that make sense to the state machine . Events usually cause changes in state , Make the state machine switch from one state to another .
state (State) It refers to a state of an object in its life cycle , An object in a particular state must satisfy certain conditions 、 Perform certain actions or wait for certain events .
transformation (Transition) It refers to a relationship between two states , Indicates that the object will perform certain actions in the first state , And will enter the second state when a certain event occurs and a certain condition is satisfied .
This time, let's take a look at the finite state machine and its actual combat .
FSM
Definition
Finite state machine ( English :finite-state machine, abbreviation :FSM) Also known as finite state automata , State machine for short , It's a mathematical model that represents finite states and behaviors such as transitions and actions between these states .
FSM We can put the model in multiple states 、 The transition conditions between multiple states are decoupled . Can make maintenance easy , The code is also more readable , And more artistic .
Source code
Examples
github On https://github.com/looplab/fsm, Yes 1.8K Star, Let's take this open source project as an example , Let's talk about FSM The concrete realization of . Open the door here 、 Take closing the door as an example , Although the state is very , But it can explain the problem well .
The location of the sample code is :https://github.com/shidawuhen/asap/blob/master/controller/various/fsm.go
package main
import (
"fmt"
"github.com/looplab/fsm"
)
type Door struct {
To string
FSM *fsm.FSM
}
func NewDoor(to string) *Door {
d := &Door{
To: to,
}
d.FSM = fsm.NewFSM(
"closed",
fsm.Events{
{
Name: "open", Src: []string{
"closed"}, Dst: "open"},
{
Name: "close", Src: []string{
"open"}, Dst: "closed"},
},
fsm.Callbacks{
// Specify state
"leave_closed": func(e *fsm.Event) {
d.leaveClose(e) },
"before_open": func(e *fsm.Event) {
d.beforeOpen(e) },
"enter_open": func(e *fsm.Event) {
d.enterOpen(e) },
"after_open": func(e *fsm.Event) {
d.afterOpen(e) },
// General status
"enter_state": func(e *fsm.Event) {
d.enterState(e) },
},
)
return d
}
func (d *Door) beforeOpen(e *fsm.Event) {
fmt.Printf("beforeOpen, The door to %s is %s\n", d.To, e.Dst)
}
func (d *Door) enterOpen(e *fsm.Event) {
fmt.Printf("enterOpen, The door to %s is %s\n", d.To, e.Dst)
}
func (d *Door) afterOpen(e *fsm.Event) {
fmt.Printf("afterOpen, The door to %s is %s\n", d.To, e.Dst)
}
func (d *Door) leaveOpen(e *fsm.Event) {
fmt.Printf("leaveOpen, The door to %s is %s\n", d.To, e.Dst)
}
func (d *Door) leaveClose(e *fsm.Event) {
fmt.Printf("leaveClose, The door to %s is %s\n", d.To, e.Dst)
}
func (d *Door) enterState(e *fsm.Event) {
fmt.Printf("The door to %s is %s\n", d.To, e.Dst)
}
func main() {
door := NewDoor("heaven")
fmt.Println(" The current state is :" + door.FSM.Current())
err := door.FSM.Event("open")
if err != nil {
fmt.Println(err)
}
fmt.Println(" The current state is :" + door.FSM.Current())
err = door.FSM.Event("close")
if err != nil {
fmt.Println(err)
}
}
Output :
* myproject go run main.go
The current state is :closed
beforeOpen, The door to heaven is open
leaveClose, The door to heaven is open
enterOpen, The door to heaven is open
The door to heaven is open
afterOpen, The door to heaven is open
The current state is :open
The door to heaven is closed
explain
- NewDoor Inside Events Store state machine information
Name: event
Src: current state
Dst: Target state
When an event occurs , If the current is Src state , Can be transformed into Dst state
- NewDoor Inside Callbacks Store switching action
Conversion actions can be divided into general conversion and specified conversion , The general conversion status format is ***_state, The format of the specified transition state is ***_ Status name
Whether general or specified transition state , All four , Corresponding to the code in the sample
What to do before entering the current state :before_**
Leave the previous state and do something :leave_**
What to do when entering the current state :enter_**
What to do after the current status execution :after_**
The order of execution is :https://www.processon.com/view/link/6289e3bd1e08533ae716e7ad
example
FSM It can be used in many states 、 Where there are many changes , Such as performance sheet . Generally, order fulfillment involves many states , And these states often change , Use FSM It will be much more convenient . There are several implementation points :
The current status should be recorded on the order
Need to maintain the state machine , There are two ways to think about
drawing : Clear information can help us quickly understand the current situation of the whole state machine
State machine storage : The state machine can be written in code or stored in the database , The format is as follows Events Shown , At least there needs to be an event 、 current state 、 Target state
- Transfer implementation
There are general transfers and designated transfers , Good general transfer logic can enhance reusability
The specified state can be implemented independently , Because the conversion code has been decoupled , Little impact on the system
- State consistency
- First calculate the target state , When all operations are completed correctly , Update order status to target status
summary
By analyzing the source code and examples , You can see the use FSM It can not only clearly maintain the state machine , And changes to the state 、 Changes to the transfer function are decoupled , Greatly reduces maintenance costs .
At the same time, through reasonable design , Give the R & D personnel great control over the state transfer operation , You can leave 、 In the top 、 Get into 、 Control at four times after completion .
In terms of friendliness , I think it's better than Go Design patterns (22)- The state pattern Better .
Information
Finite state machine FSM Detailed explanation ( One )
FSM Learning notes
Two ways to write a state machine
Gofsm
https://github.com/looplab/fsm
Last
If you like my article , You can pay attention to my official account. ( Hot programmer )
My personal blog is :https://shidawuhen.github.io/
Review of previous articles :
边栏推荐
- 社交社区论坛APP超高颜值UI界面
- Export the entire Oracle Database
- ORM use of node -serialize
- Express abstract classes and methods
- 并网-低电压穿越与孤岛并存分析
- Integer case study of packaging
- 【习题七】【数据库原理】
- [network counting] Chapter 3 data link layer (2) flow control and reliable transmission, stop waiting protocol, backward n frame protocol (GBN), selective retransmission protocol (SR)
- 01 three solutions to knapsack problem (greedy dynamic programming branch gauge)
- [problem exploration and solution of one or more filters or listeners failing to start]
猜你喜欢
When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
Two solutions of leetcode101 symmetric binary tree (recursion and iteration)
Solve the problem of VI opening files with ^m at the end
Leetcode234 palindrome linked list
Xctf mobile--app1 problem solving
[problem exploration and solution of one or more filters or listeners failing to start]
Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
How to convert a decimal number to binary in swift
Method overloading and rewriting
有限状态机FSM
随机推荐
[data mining review questions]
Two solutions of leetcode101 symmetric binary tree (recursion and iteration)
Grid connection - Analysis of low voltage ride through and island coexistence
Kotlin - 改良装饰者模式
C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - cases without asynchronous
Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
OpenHarmony应用开发之ETS开发方式中的Image组件
Deeply understand the mvcc mechanism of MySQL
The upward and downward transformation of polymorphism
【习题五】【数据库原理】
Brief introduction to mvcc
解决 System has not been booted with systemd as init system (PID 1). Can‘t operate.
自抗扰控制器七-二阶 LADRC-PLL 结构设计
Attack and defense world mobile--ph0en1x-100
Image component in ETS development mode of openharmony application development
[exercice 7] [principe de la base de données]
(最新版) Wifi分销多开版+安装框架
Integer case study of packaging
GaN图腾柱无桥 Boost PFC(单相)七-PFC占空比前馈
【習題七】【數據庫原理】