当前位置:网站首页>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 :
边栏推荐
- Everything comes to him who waits
- 我的创作纪念日:五周年
- 如何在微信小程序中获取用户位置?
- 2022-01-27 redis cluster brain crack problem analysis
- [ArcGIS user defined script tool] vector file generates expanded rectangular face elements
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第三章习题】
- 低代码平台国际化多语言(i18n)技术方案
- The foreground uses RSA asymmetric security to encrypt user information
- Nodejs+express+mysql realizes login function (including verification code)
- Harmonic current detection based on synchronous coordinate transformation
猜你喜欢
![[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number](/img/9d/6118b699c0d90810638f9b08d4f80a.jpg)
[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number

Image component in ETS development mode of openharmony application development
![[review questions of database principles]](/img/c3/81d192a40bcc4f5d72fcbe76c708bb.png)
[review questions of database principles]

Low code platform international multilingual (I18N) technical solution

Xctf mobile--rememberother problem solving

How to get user location in wechat applet?

sitesCMS v3.1.0发布,上线微信小程序
![[ArcGIS user defined script tool] vector file generates expanded rectangular face elements](/img/39/0b31290798077cb8c355fbd058e4d3.png)
[ArcGIS user defined script tool] vector file generates expanded rectangular face elements

Attack and defense world mobile--ph0en1x-100

Method overloading and rewriting
随机推荐
Tianyi ty1208-z brush machine detailed tutorial (free to remove)
Export the entire Oracle Database
Enter the length of three sides of the triangle through the user, and calculate the area of the triangle, where the length is a real number
Sitescms v3.1.0 release, launch wechat applet
SQL learning notes (I)
[comprehensive question] [Database Principle]
【判断题】【简答题】【数据库原理】
Node. Js: use of express + MySQL
OpenHarmony应用开发之ETS开发方式中的Image组件
Deeply understand the mvcc mechanism of MySQL
(latest version) WiFi distribution multi format + installation framework
context. Getexternalfilesdir() is compared with the returned path
How to get user location in wechat applet?
sitesCMS v3.0.2发布,升级JFinal等依赖
C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: what is entrustment? P238
Dojo tutorials:getting started with deferrals source code and example execution summary
C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: delegatesamplep245
I'm too lazy to write more than one character
When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
Swift Error Handling