教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang 状态机_Go语言的有限状态机。

golang 状态机_Go语言的有限状态机。

发布时间:2021-05-26   编辑:jiaochengji.com
教程集为您提供golang 状态机,Go语言的有限状态机。等资源,欢迎您收藏本站,我们将为您提供最新的golang 状态机,Go语言的有限状态机。资源

golang 状态机

In computation theory, the Finite State Machine (FSM) is those machines that can have a finite number of states at a given time. These machines are used in our daily life such as; vending machines, elevators, traffic lights, etc. Not only in hardware these machines are used in the software also.

在计算理论中,有限状态机(FSM)是在给定时间可以具有有限数量状态的机器。 这些机器用于我们的日常生活中,例如; 自动售货机,电梯,交通信号灯等。这些机器不仅用于硬件,而且还用于软件。

什么是FSM? (What is FSM?)

They are the process to model stateful, reactive systems i.e in behavior-driven development. FSM based programming is a powerful tool to model complicated state transitions, it could significantly simplify our programs.

它们是对有状态的React性系统进行建模的过程,即在行为驱动的开发中。 基于FSM的编程是建模复杂状态转换的强大工具,它可以大大简化我们的程序。

For a functional programming standpoint, FSM is a function that takes in four parameters; initial state, transition function, set of states, event, and then return the next state at which the machine can be.

从功能编程的角度来看,FSM是一个具有四个参数的函数。 初始状态,转换函数,状态集,事件,然后返回机器可以处于的下一个状态。

Wikipedia 维基百科

In the above state machine, the states are locked and unlocked . The initial state is locked described by a black arrow pointing. The events are coin and push similarly, the state transition function can be described by a table.

在上述状态机中,状态被lockedunlocked 。 初始状态被locked ,用黑色箭头表示。 事件是coinpush类似,状态转换函数可以用表格描述。

With this, we can see how our state machine function can give out the next state when we provide it with the initial state, number of states, transition function (described by the table), and event.

这样,我们便可以了解到状态机功能如何向其提供初始状态,状态数,转换函数(由表描述)和事件,从而发出下一个状态。

In automata theory, there are different types of state machines and various other state-based concepts so, for simplicity, I am only talking about the basic finite state machine.

在自动机理论中,有不同类型的状态机和各种其他基于状态的概念,因此,为简单起见,我仅讨论基本的有限状态机。

状态说明图 (FIGURE TO STATE DESCRIPTION)

I know it would be better if we could directly send our diagram into the machine and it would change the state based on the diagram (like; BPMN which is also a kind of state machine built just for business process modeling)

我知道最好将图表直接发送到机器中,并且根据图表更改状态(例如BPMN,这也是一种仅用于业务流程建模的状态机),这样会更好。

Let’s define our struct that would be used to model our figure into code. (this description is inspired by xstate, a state charts library in JavaScript)

让我们定义将用于将图形建模为代码的结构。 (此描述的灵感来自xstate ,这是JavaScript中的状态图库)

// MachineTransition transition map
type MachineTransition struct {
	To      string
}


// TransitionMap map with transitions
type TransitionMap map[string]MachineTransition


// MachineState is State of machine
type MachineState struct {
	On TransitionMap
}


// StateMap maps state
type StateMap map[string]MachineState


// Machine datatype
type Machine struct {
	Initial     string
	current     string
	States      StateMap
}

Here, The struct machine describes all our parameters described previously.

在这里,struct机器描述了我们前面描述的所有参数。

  • Machine struct defines the initial state, current state, and all the states contained in the machine.

    Machine结构定义了初始状态,当前状态以及机器中包含的所有状态。

  • The type StateMap is used to describe all the state transitions that are present in the machine.

    StateMap类型用于描述机器中存在的所有状态转换。

  • Type TransitionMap describes the machine transition when a certain event occurs.

    类型TransitionMap描述发生特定事件时的机器转换。

https://xstate.js.org/viz/ https://xstate.js.org/viz/生成

The switch toggling from one state to another state as described in the figure above can be described as;

如上图所示,从一种状态切换到另一种状态的开关可以描述为:

machine := statemachine.Machine{
    Initial: "on",
    States: statemachine.StateMap{
        "on": statemachine.MachineState{
            On: statemachine.TransitionMap{
                "TOGGLE": statemachine.MachineTransition{
                    To: "off",
                },
            },
        },
        "off": statemachine.MachineState{
            On: statemachine.TransitionMap{
                "TOGGLE": statemachine.MachineTransition{
                    To: "on",
                },
            },
        },
    },
}

You can see in the description above that when the machine is on and event TOGGLE is sent to machine it should transition to off state similarly when it is in off state and TOGGLE is sent to the machine is should transition to on state.

您可以在上面的描述中看到,当计算机on并且事件TOGGLE发送到计算机时,它应该转换为off状态,类似于当计算机处于off状态并且将TOGGLE发送到计算机时应该转换为on状态。

Now we have described the machine using our format but the engine that transitions the state from one to another is still not built.

现在,我们已经使用格式描述了机器,但是仍未构建将状态从一种转换为另一种的引擎。

过渡引擎 (TRANSITION ENGINE)

The transition engine should take in the state description and build the machine that can change state based on provided events. Let’s add an interface to Machine struct that has Transition function and Current function that returns the current state the machine is in.

过渡引擎应该接受状态描述,并构建可以根据提供的事件更改状态的机器。 让我们向Machine结构添加一个接口,该接口具有Transition函数和Current函数,该函数返回计算机所处的当前状态。

// IMachine machine interface
type IMachine interface {
	Transition() string
	Current() string
}


// Current returns current state
func (m *Machine) Current() string {
	if m.current == "" {
		return m.Initial
	}
	return m.current
}


// Transition transitions to next state
func (m *Machine) Transition(event string) string {
	current := m.Current()
	transitions := m.States[current].On
	for evt := range transitions {
		if evt == event {
			next := transitions[evt].To
			m.current = next
			return next
		}
	}
	return current
}

In the above code we can see that;

在上面的代码中我们可以看到;

  • From line #19 to #25 we are looping over the transition present in the machine based on the current state and then if the event matches the event string passed to the function then the next state is returned. If not then the current state is returned (state change didn’t occur)

    从第19行到第25行,我们基于当前状态循环遍历机器中存在的转换,然后如果事件与传递给函数的event字符串匹配,则返回下一个状态。 如果不是,则返回当前状态(未发生状态更改)

  • From line #8 to #13, we are declaring the function that returns the current state of the state machine.

    从第8行到第13行,我们声明了返回状态机当前状态的函数。

Now, let’s use the functions. The function can be used using;

现在,让我们使用这些功能。 该功能可以通过以下方式使用:

output := machine.Transition("TOGGLE")

and we can see that the machine has actually transitioned into another state.

我们可以看到机器实际上已经过渡到另一种状态。

最终密码 (FINAL CODE)

Final code of the machine description and toggling state will look like;

机器描述和切换状态的最终代码将如下所示;

package main


import (
	"fmt"


	"github.com/dipeshdulal/statemachine"
)


func main(){
  machine := statemachine.Machine{
      ID:      "machine-1",
      Initial: "on",
      States: statemachine.StateMap{
          "on": statemachine.MachineState{
              On: statemachine.TransitionMap{
                  "TOGGLE": statemachine.MachineTransition{
                      To: "off",
                  },
              },
          },
          "off": statemachine.MachineState{
              On: statemachine.TransitionMap{
                  "TOGGLE": statemachine.MachineTransition{
                      To: "on",
                  },
              },
          },
      },
  }
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
}

We could add some other functionality into our little FSM library like;

我们可以在我们的小FSM库中添加其他功能,例如;

  • External condition for the transition

    过渡的外部条件

  • State change listeners etc.

    状态更改侦听器等

You can check out; https://github.com/dipeshdulal/statemachine for full code of the machine and some examples present in the repository.

您可以签出; https://github.com/dipeshdulal/statemachine ,其中包含机器的完整代码以及存储库中提供的一些示例。

The state description for the lock-unlock machine presented in the figure above is shown here

上图显示了上锁机器的状态说明

Follow me on GitHub: https://github.com/dipeshdulal

在GitHub上关注我: https : //github.com/dipeshdulal

For basic concepts on golang check; https://github.com/dipeshdulal/learning-golang

有关golang检查的基本概念; https://github.com/dipeshdulal/learning-golang

Have a good day.

祝你有美好的一天。

翻译自: https://medium.com/wesionary-team/finite-state-machines-with-go-lang-ccd20e329a7b

golang 状态机

到此这篇关于“golang 状态机_Go语言的有限状态机。”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang 状态机_Go语言的有限状态机。
go并发编程笔记
go语言核心编程_Go语言核心编程李文塔
Go语言学习之reflect包(The way to go)
goroutine 调度器
联想Storage S3200/2200存储,Vdisk的状态有哪几种?
recover 没有捕获异常_GO语言异常处理机制panic和recover分析
go语言有哪些优势?Go语言的核心特性有哪些
Go 语言的核心优势
Golang同步机制的实现

[关闭]
~ ~