当前位置:网站首页>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 :
边栏推荐
- [combinatorics] permutation and combination (multiple set permutation | multiple set full permutation | multiple set incomplete permutation all elements have a repetition greater than the permutation
- C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: what is entrustment? P238
- 对业务的一些思考
- studio All flavors must now belong to a named flavor dimension. Learn more
- Kotlin notes - popular knowledge points asterisk (*)
- How to convert a decimal number to binary in swift
- Brief introduction to mvcc
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第三章习题】
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第七章习题】
- OpenHarmony应用开发之ETS开发方式中的Image组件
猜你喜欢

Huffman coding experiment report

解决 System has not been booted with systemd as init system (PID 1). Can‘t operate.
![[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

Swift bit operation exercise

Image component in ETS development mode of openharmony application development

4. Wireless in vivo nano network: electromagnetic propagation model and key points of sensor deployment

Quick learning 1.8 front and rear interfaces

2022-02-09 survey of incluxdb cluster

Xctf mobile--app1 problem solving

并网-低电压穿越与孤岛并存分析
随机推荐
剑指 Offer 16. 数值的整数次方
Kotlin notes - popular knowledge points asterisk (*)
Enable SASL authentication for memcached
【习题五】【数据库原理】
sitesCMS v3.0.2发布,升级JFinal等依赖
[exercise 7] [Database Principle]
Solve the problem of VI opening files with ^m at the end
Xctf mobile--app3 problem solving
Exploration of sqoop1.4.4 native incremental import feature
【综合题】【数据库原理】
(latest version) WiFi distribution multi format + installation framework
How to convert a decimal number to binary in swift
C graphical tutorial (Fourth Edition)_ Chapter 18 enumerator and iterator: enumerator samplep340
2022-02-11 practice of using freetsdb to build an influxdb cluster
An example of newtonjason
Define a list, store n integers, and calculate the length, maximum value, minimum value and average value of the list
Ali & ant self developed IDE
Create a dojo progress bar programmatically: Dojo ProgressBar
【Colab】【使用外部数据的7种方法】
The foreground uses RSA asymmetric security to encrypt user information