├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── callback.go
├── fsm.go
├── fsm_test.go
├── go.mod
└── state.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled Object files, Static and Dynamic libs (Shared Objects)
2 | *.o
3 | *.a
4 | *.so
5 |
6 | # Folders
7 | _obj
8 | _test
9 |
10 | # Architecture specific extensions/prefixes
11 | *.[568vq]
12 | [568vq].out
13 |
14 | *.cgo1.go
15 | *.cgo2.c
16 | _cgo_defun.c
17 | _cgo_gotypes.go
18 | _cgo_export.*
19 |
20 | _testmain.go
21 |
22 | *.exe
23 | *.test
24 | *.prof
25 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 |
3 | go:
4 | - 1.6.3
5 | - 1.7.3
6 |
7 | notifications:
8 | email:
9 | recipients: smallnest@gmail.com
10 | on_success: change
11 | on_failure: always
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://opensource.org/licenses/Apache-2.0) [](http://godoc.org/github.com/smallnest/gofsm)  [](http://gocover.io/github.com/smallnest/gofsm) [](https://goreportcard.com/report/github.com/smallnest/gofsm)
2 |
3 |
4 |
5 | [gofsm](https://github.com/smallnest/gofsm)是一个简单、小巧而又特色的有限状态机(FSM)。
6 |
7 | github已经有了很多个状态机的实现,比如文末列举的一些,还为什么要再发明轮子呢?
8 |
9 | 原因在于这些状态机有一个特点,就是一个状态机维护一个对象的状态,这样一个状态机就和一个具体的图像实例关联在一起,在有些情况下,这没有什么问题,而且是很好的设计,而且比较符合状态机的定义。但是在有些情况下,当我们需要维护成千上百个对象的时候,需要创建成千上百个状态机对象,这其实是很大的浪费,因为在大部分情况下,对象本身自己会维护/保持自己当前的状态,我们只需把对象当前的状态传递给一个共用的状态机就可以了,也就是gofsm本身是“stateless”,本身它包维护一个或者多个对象的状态,所有需要的输入由调用者输入,它只负责状态的转换的逻辑,所以它的实现非常的简洁实用,这是创建gofsm的一个目的。
10 |
11 | 第二个原因它提供了Moore和Mealy两种状态机的统一接口,并且提供了UML状态机风格的Action处理,以程序员更熟悉的方式处理状态的改变。
12 |
13 | 第三个原因,当我们谈论起状态机的时候,我们总会画一个状态转换图,大家可以根据这这张图进行讨论、设计、实现和验证状态的迁移。但是对于代码来说,实现真的和你的设计是一致的吗,你怎么保证?gofsm提供了一个简单的方法,那就是它可以输出图片或者pdf文件,你可以利用输出的状态机图和你的设计进行比较,看看实现和设计是否一致。
14 |
15 | 
16 |
17 | ## 有限状态机
18 | 有限状态机(finite-state machine)常常用于计算机程序和时序逻辑电路的设计数学模型。它被看作是一种抽象的机器,可以有有限个状态。任意时刻这个机器只有唯一的一个状态,这个状态称为当前状态。当有外部的事件或者条件被触发,它可以从一个状态转换到另一个状态,这就是转换(transition)。一个FSM就是由所有的状态、初始状态和每个转换的触发条件所定义。有时候,当这个转换发生的时候,我们可以要执行一些事情,我们称之为动作(Action)。
19 |
20 | 现实情况中,我们实际上遇到了很多的这种状态机的情况,只不过我们并没有把它们抽象出来,比如路口的红绿灯,总是在红、黄、绿的状态之间转变,比如电梯的状态,包括开、关、上、下等几个状态。
21 |
22 | 有限状态机可以有效清晰的为一大堆的问题建立模型,大量应用于电子设计、通讯协议、语言解析和其它的工程应用中,比如TCP/IP协议栈。
23 |
24 | 
25 |
26 | 以一个转门为例,这种专门在一些会展、博物馆、公园的门口很常见,顾客可以投币或者刷卡刷票进入,我们下面以投币(Coin)统称这个触发事件。如果你不投币,闸门是锁着的,你推不动它的转臂,而且投一次币只能进去一个人,过去之后闸门又是锁着的,挺智能的 :)。
27 |
28 | 
29 |
30 | 如果我们抽象出来它的状态图,可以用下图表示:
31 | 
32 |
33 | 它有两个状态:`Locked`、`Unlocked`。有两个输入(input)会影响它的状态,投币(coin)和推动转臂(push)。
34 | 1. 在Locked状态, push没有作用。不管比push多少次闸门的状态还是lock
35 | 2. 在Locked状态,投币会让闸门开锁,闸门可以让一个人通过
36 | 3. 在Unlocked状态,投币不起作用,闸门还是开着
37 | 4. 在Unlocked状态,如果有人push通过,人通过后闸门会由Unlocked状态转变成Locked状态。
38 |
39 | 这是一个简单的闸门的状态转换,却是一个很好的理解状态的典型例子。
40 |
41 | 以表格来表示:
42 |
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 |
43 |
44 |
45 | UML也有状态图的改变,它扩展了FSM的概念,提供了层次化的嵌套状态(Hierarchically nested states)和正交区域(orthogonal regions),当然这和本文没有太多的关系,有兴趣的读者可以找UML的资料看看。但是它提供了一个很好的概念,也就是动作(Action)。就像Mealy状态机所需要的一样,动作依赖系统的状态和触发事件,而它的Entry Action和Exit Action,却又像Moore 状态机一样,不依赖输入,只依赖状态。所以UML的动作有三种,一种是事件被处理的时候,状态机会执行特定的动作,比如改变变量、执行I/O、调用方法、触发另一个事件等。而离开一个状态,可以执行Exit action,进入一个状态,则执行Entry action。记住,收到一个事件,对象的状态不会改变,比如上边闸门的例子,在Locked状态下push多少次状态都没改变,这这种情况下,不会执行Exit和Entry action。
46 |
47 | gofsm提供了这种扩展的模型,当然如果你不想使用这种扩展,你也可以不去实现Entry和Exit。
48 |
49 |
50 | 可以提到了两种状态机,这两种状态机是这样来区分的:
51 |
52 | * **Moore machine**
53 | Moore状态机只使用entry action,输出只依赖状态,不依赖输入。
54 | * **Mealy machine**
55 | Mealy状态机只使用input action,输出依赖输入input和状态state。使用这种状态机通常可以减少状态的数量。
56 |
57 | gofsm提供了一个通用的接口,你可以根据需要确定使用哪个状态机。从软件开发的实践上来看,有时候你并不一定要关注状态机的区分,而是清晰的抽象、设计你所关注的对象的状态、触发条件以及要执行的动作。
58 |
59 |
60 | ## gofsm
61 | gofsm参考了 [elimisteve/fsm](https://github.com/elimisteve/fsm) 的实现,实现了一种单一状态机处理多个对象的方法,并且提供了输出状态图的功能。
62 |
63 | 它除了定义对象的状态外,还定义了触发事件以及处理的Action,这些都是通过字符串来表示的,在使用的时候很容易的和你的对象、方法对应起来。
64 |
65 | 使用gofsm也很简单,当然第一步将库拉到本地:
66 | ```sh
67 | go get -u github.com/smallnest/gofsm
68 | ```
69 |
70 | 我们以上面的闸门为例,看看gofsm是如何使用的。
71 |
72 | 注意下面的单个状态机可以处理并行地的处理多个闸门的状态改变,虽然例子中只生成了一个闸门对象。
73 |
74 | 首先定义一个闸门对象,它包含一个State,表示它当前的状态:
75 | ```go
76 | type Turnstile struct {
77 | ID uint64
78 | EventCount uint64 //事件统计
79 | CoinCount uint64 //投币事件统计
80 | PassCount uint64 //顾客通过事件统计
81 | State string //当前状态
82 | States []string //历史经过的状态
83 | }
84 | ```
85 |
86 | 状态机的初始化简单直接:
87 | ```go
88 | func initFSM() *StateMachine {
89 | delegate := &DefaultDelegate{P: &TurnstileEventProcessor{}}
90 |
91 | transitions := []Transition{
92 | Transition{From: "Locked", Event: "Coin", To: "Unlocked", Action: "check"},
93 | Transition{From: "Locked", Event: "Push", To: "Locked", Action: "invalid-push"},
94 | Transition{From: "Unlocked", Event: "Push", To: "Locked", Action: "pass"},
95 | Transition{From: "Unlocked", Event: "Coin", To: "Unlocked", Action: "repeat-check"},
96 | }
97 |
98 | return NewStateMachine(delegate, transitions...)
99 | }
100 | ```
101 |
102 | 你定义好转换对应关系`transitions`,一个`Transition`代表一个转换,从某个状态到另外一个状态,触发的事件名,要执行的Action。
103 | 因为Action是字符串,所以你需要实现`delegate`将Action和对应的要处理的方法对应起来。
104 |
105 | 注意from和to的状态可以一样,在这种情况下,状态没有发生改变,只是需要处理Action就可以了。
106 |
107 | 如果Action为空,也就是不需要处理事件,只是发生状态的改变而已。
108 |
109 | 处理Action的类型如下:
110 | ```go
111 | type TurnstileEventProcessor struct{}
112 |
113 | func (p *TurnstileEventProcessor) OnExit(fromState string, args []interface{}) {
114 | ……
115 | }
116 |
117 | func (p *TurnstileEventProcessor) Action(action string, fromState string, toState string, args []interface{}) {
118 | ……
119 | }
120 |
121 | func (p *TurnstileEventProcessor) OnEnter(toState string, args []interface{}) {
122 | ……
123 | }
124 | ```
125 |
126 | 然后我们就可以触发一些事件看看闸门的状态机是否正常工作:
127 | ```go
128 | ts := &Turnstile{
129 | ID: 1,
130 | State: "Locked",
131 | States: []string{"Locked"},
132 | }
133 | fsm := initFSM()
134 |
135 | //推门
136 | //没刷卡/投币不可进入
137 | err := fsm.Trigger(ts.State, "Push", ts)
138 | if err != nil {
139 | t.Errorf("trigger err: %v", err)
140 | }
141 |
142 | //推门
143 | //没刷卡/投币不可进入
144 | err = fsm.Trigger(ts.State, "Push", ts)
145 | if err != nil {
146 | t.Errorf("trigger err: %v", err)
147 | }
148 |
149 | //刷卡或者投币
150 | //不容易啊,终于解锁了
151 | err = fsm.Trigger(ts.State, "Coin", ts)
152 | if err != nil {
153 | t.Errorf("trigger err: %v", err)
154 | }
155 |
156 | //刷卡或者投币
157 | //这时才解锁
158 | err = fsm.Trigger(ts.State, "Coin", ts)
159 | if err != nil {
160 | t.Errorf("trigger err: %v", err)
161 | }
162 |
163 | //推门
164 | //这时才能进入,进入后闸门被锁
165 | err = fsm.Trigger(ts.State, "Push", ts)
166 | if err != nil {
167 | t.Errorf("trigger err: %v", err)
168 | }
169 |
170 | //推门
171 | //无法进入,闸门已锁
172 | err = fsm.Trigger(ts.State, "Push", ts)
173 | if err != nil {
174 | t.Errorf("trigger err: %v", err)
175 | }
176 |
177 | lastState := Turnstile{
178 | ID: 1,
179 | EventCount: 6,
180 | CoinCount: 2,
181 | PassCount: 1,
182 | State: "Locked",
183 | States: []string{"Locked", "Unlocked", "Locked"},
184 | }
185 |
186 | if !compareTurnstile(&lastState, ts) {
187 | t.Errorf("Expected last state: %+v, but got %+v", lastState, ts)
188 | } else {
189 | t.Logf("最终的状态: %+v", ts)
190 | }
191 | ```
192 |
193 | 如果想将状态图输出图片,可以调用下面的方法,它实际是调用graphviz生成的,所以请确保你的机器上是否安装了这个软件,你可以执行`dot -h`检查一下:
194 | ```go
195 | fsm.Export("state.png")
196 | ```
197 | 生成的图片就是文首的闸门的状态机的图片。
198 |
199 | 如果你想定制graphviz的参数,你可以调用另外一个方法:
200 | ```go
201 | func (m *StateMachine) ExportWithDetails(outfile string, format string, layout string, scale string, more string) error
202 | ```
203 |
204 | ## 其它Go语言实现的FSM
205 | 如果你发现gofsm的功能需要改进,或者有一些想法、或者发现了bug,请不用迟疑,在[issue](https://github.com/smallnest/gofsm/issues)中提交你的意见和建议,我会及时的进行反馈。
206 |
207 | 如果你觉得本项目有用,或者将来可能会使用,请star这个项目 [smallnest/gofsm](https://github.com/smallnest/gofsm)。
208 |
209 | 如果你想比较其它的Go语言实现的fsm,可以参考下面的列表:
210 | * [elimisteve/fsm](https://github.com/elimisteve/fsm)
211 | * [looplab/fsm](https://github.com/looplab/fsm)
212 | * [vaughan0/go-fsm](https://github.com/vaughan0/go-fsm)
213 | * [WatchBeam/fsm](https://github.com/WatchBeam/fsm)
214 | * [DiscoViking/fsm](https://github.com/DiscoViking/fsm)
215 | * [autocube/hsm](https://github.com/autocube/hsm)
216 | * [theckman/go-fsm](https://github.com/theckman/go-fsm)
217 | * [Zumata/fsm](https://github.com/Zumata/fsm)
218 | * [syed/go-fsm](https://github.com/syed/go-fsm)
219 | * [go-rut/fsm](https://github.com/go-rut/fsm)
220 | * [yandd/fsm](https://github.com/yandd/fsm)
221 | * [go-trellis/fsm](https://github.com/go-trellis/fsm)
222 | * ……
223 |
224 | ## 参考资料
225 | 1. https://en.wikipedia.org/wiki/Finite-state_machine
226 |
--------------------------------------------------------------------------------
/callback.go:
--------------------------------------------------------------------------------
1 | package fsm
2 |
3 | // EventProcessor defines OnExit, Action and OnEnter actions.
4 | type EventProcessor interface {
5 | // OnExit Action handles exiting a state
6 | OnExit(fromState string, args []interface{})
7 | // Action is used to handle transitions
8 | Action(action string, fromState string, toState string, args []interface{}) error
9 | // OnActionFailure failed to execute the Action
10 | OnActionFailure(action string, fromState string, toState string, args []interface{}, err error)
11 | // OnExit Action handles entering a state
12 | OnEnter(toState string, args []interface{})
13 | }
14 |
15 | // DefaultDelegate is a default delegate.
16 | // it splits processing of actions into three actions: OnExit, Action and OnEnter.
17 | type DefaultDelegate struct {
18 | P EventProcessor
19 | }
20 |
21 | // HandleEvent implements Delegate interface and split HandleEvent into three actions.
22 | func (dd *DefaultDelegate) HandleEvent(action string, fromState string, toState string, args []interface{}) error {
23 | if fromState != toState {
24 | dd.P.OnExit(fromState, args)
25 | }
26 |
27 | err := dd.P.Action(action, fromState, toState, args)
28 | if err != nil {
29 | dd.P.OnActionFailure(action, fromState, toState, args, err)
30 | return err
31 | }
32 |
33 | if fromState != toState {
34 | dd.P.OnEnter(toState, args)
35 | }
36 |
37 | return nil
38 | }
39 |
--------------------------------------------------------------------------------
/fsm.go:
--------------------------------------------------------------------------------
1 | // gofsm is a simple, featured FSM implementation that has some different features with other FSM implementation.
2 | // One feature of gofsm is it doesn't persist/keep states of objects. When it processes transitions, you must pass current states to id, so you can look gofsm as a "stateless" state machine. This benefit is one gofsm instance can be used to handle transitions of a lot of object instances, instead of creating a lot of FSM instances. Object instances maintain their states themselves.
3 | // Another feature is it provides a common interface for Moore and Mealy FSM. You can implement corresponding methods (OnExit, Action, OnEnter) for those two FSM.
4 | // The third interesting feature is you can export configured transitions into a state diagram. A picture is worth a thousand words.
5 |
6 | // Style of gofsm refers to implementation of https://github.com/elimisteve/fsm.
7 |
8 | package fsm
9 |
10 | import (
11 | "fmt"
12 | "os/exec"
13 | "runtime"
14 | "strings"
15 | )
16 |
17 | // Transition is a state transition and all data are literal values that simplifies FSM usage and make it generic.
18 | type Transition struct {
19 | From string
20 | Event string
21 | To string
22 | Action string
23 | }
24 |
25 | // Delegate is used to process actions. Because gofsm uses literal values as event, state and action, you need to handle them with corresponding functions. DefaultDelegate is the default delegate implementation that splits the processing into three actions: OnExit Action, Action and OnEnter Action. you can implement different delegates.
26 | type Delegate interface {
27 | // HandleEvent handles transitions
28 | HandleEvent(action string, fromState string, toState string, args []interface{}) error
29 | }
30 |
31 | // StateMachine is a FSM that can handle transitions of a lot of objects. delegate and transitions are configured before use them.
32 | type StateMachine struct {
33 | delegate Delegate
34 | transitions []Transition
35 | }
36 |
37 | // Error is an error when processing event and state changing.
38 | type Error interface {
39 | error
40 | BadEvent() string
41 | CurrentState() string
42 | }
43 |
44 | type smError struct {
45 | badEvent string
46 | currentState string
47 | }
48 |
49 | func (e smError) Error() string {
50 | return fmt.Sprintf("state machine error: cannot find transition for event [%s] when in state [%s]\n", e.badEvent, e.currentState)
51 | }
52 |
53 | func (e smError) BadEvent() string {
54 | return e.badEvent
55 | }
56 |
57 | func (e smError) CurrentState() string {
58 | return e.currentState
59 | }
60 |
61 | // NewStateMachine creates a new state machine.
62 | func NewStateMachine(delegate Delegate, transitions ...Transition) *StateMachine {
63 | return &StateMachine{delegate: delegate, transitions: transitions}
64 | }
65 |
66 | // Trigger fires a event. You must pass current state of the processing object, other info about this object can be passed with args.
67 | func (m *StateMachine) Trigger(currentState string, event string, args ...interface{}) error {
68 | trans := m.findTransMatching(currentState, event)
69 | if trans == nil {
70 | return smError{event, currentState}
71 | }
72 |
73 | var err error
74 | if trans.Action != "" {
75 | err = m.delegate.HandleEvent(trans.Action, currentState, trans.To, args)
76 | }
77 | return err
78 | }
79 |
80 | // findTransMatching gets corresponding transition according to current state and event.
81 | func (m *StateMachine) findTransMatching(fromState string, event string) *Transition {
82 | for _, v := range m.transitions {
83 | if v.From == fromState && v.Event == event {
84 | return &v
85 | }
86 | }
87 | return nil
88 | }
89 |
90 | // Export exports the state diagram into a file.
91 | func (m *StateMachine) Export(outfile string) error {
92 | return m.ExportWithDetails(outfile, "png", "dot", "72", "-Gsize=10,5 -Gdpi=200")
93 | }
94 |
95 | // ExportWithDetails exports the state diagram with more graphviz options.
96 | func (m *StateMachine) ExportWithDetails(outfile string, format string, layout string, scale string, more string) error {
97 | dot := `digraph StateMachine {
98 |
99 | rankdir=LR
100 | node[width=1 fixedsize=true shape=circle style=filled fillcolor="darkorchid1" ]
101 |
102 | `
103 |
104 | for _, t := range m.transitions {
105 | link := fmt.Sprintf(`%s -> %s [label="%s | %s"]`, t.From, t.To, t.Event, t.Action)
106 | dot = dot + "\r\n" + link
107 | }
108 |
109 | dot = dot + "\r\n}"
110 | cmd := fmt.Sprintf("dot -o%s -T%s -K%s -s%s %s", outfile, format, layout, scale, more)
111 |
112 | return system(cmd, dot)
113 | }
114 |
115 | func system(c string, dot string) error {
116 |
117 | var cmd *exec.Cmd
118 | if runtime.GOOS == "windows" {
119 | cmd = exec.Command(`cmd`, `/C`, c)
120 | } else {
121 | cmd = exec.Command(`/bin/sh`, `-c`, c)
122 | }
123 | cmd.Stdin = strings.NewReader(dot)
124 | return cmd.Run()
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/fsm_test.go:
--------------------------------------------------------------------------------
1 | package fsm
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "log"
7 | "math/rand"
8 | "testing"
9 | "time"
10 | )
11 |
12 | type Turnstile struct {
13 | ID uint64
14 | EventCount uint64
15 | CoinCount uint64
16 | PassCount uint64
17 | State string
18 | States []string
19 | }
20 |
21 | // TurnstileEventProcessor is used to handle turnstile actions.
22 | type TurnstileEventProcessor struct{}
23 |
24 | func (p *TurnstileEventProcessor) OnExit(fromState string, args []interface{}) {
25 | t := args[0].(*Turnstile)
26 | if t.State != fromState {
27 | panic(fmt.Errorf("转门 %v 的状态与期望的状态 %s 不一致,可能在状态机外被改变了", t, fromState))
28 | }
29 |
30 | log.Printf("转门 %d 从状态 %s 改变", t.ID, fromState)
31 | }
32 |
33 | func (p *TurnstileEventProcessor) Action(action string, fromState string, toState string, args []interface{}) error {
34 | t := args[0].(*Turnstile)
35 | t.EventCount++
36 |
37 | switch action {
38 | case "pass": //用户通过的action
39 | t.PassCount++
40 | case "check", "repeat-check": //刷卡或者投币的action
41 | if t.CoinCount > 0 { // repeat-check
42 | return errors.New("转门暂时故障")
43 | }
44 |
45 | t.CoinCount++
46 | default: //其它action
47 | }
48 |
49 | return nil
50 | }
51 |
52 | func (p *TurnstileEventProcessor) OnEnter(toState string, args []interface{}) {
53 | t := args[0].(*Turnstile)
54 | t.State = toState
55 | t.States = append(t.States, toState)
56 |
57 | log.Printf("转门 %d 的状态改变为 %s ", t.ID, toState)
58 | }
59 |
60 | func (p *TurnstileEventProcessor) OnActionFailure(action string, fromState string, toState string, args []interface{}, err error) {
61 | t := args[0].(*Turnstile)
62 |
63 | log.Printf("转门 %d 的状态从 %s to %s 改变失败, 原因: %v", t.ID, fromState, toState, err)
64 | }
65 |
66 | func TestFSM(t *testing.T) {
67 | rand.Seed(time.Now().UnixNano())
68 |
69 | ts := &Turnstile{
70 | ID: 1,
71 | State: "Locked",
72 | States: []string{"Locked"},
73 | }
74 | fsm := initFSM()
75 |
76 | //推门
77 | //没刷卡/投币不可进入
78 | err := fsm.Trigger(ts.State, "Push", ts)
79 | if err != nil {
80 | t.Errorf("trigger err: %v", err)
81 | }
82 |
83 | //推门
84 | //没刷卡/投币不可进入
85 | err = fsm.Trigger(ts.State, "Push", ts)
86 | if err != nil {
87 | t.Errorf("trigger err: %v", err)
88 | }
89 |
90 | //刷卡或者投币
91 | //不容易啊,终于解锁了
92 | err = fsm.Trigger(ts.State, "Coin", ts)
93 | if err != nil {
94 | t.Errorf("trigger err: %v", err)
95 | }
96 |
97 | //刷卡或者投币
98 | //无用的投币, 测试Action执行失败
99 | err = fsm.Trigger(ts.State, "Coin", ts)
100 | if err != nil {
101 | t.Logf("trigger err: %v", err)
102 | }
103 |
104 | //推门
105 | //这时才能进入,进入后闸门被锁
106 | err = fsm.Trigger(ts.State, "Push", ts)
107 | if err != nil {
108 | t.Errorf("trigger err: %v", err)
109 | }
110 |
111 | //推门
112 | //无法进入,闸门已锁
113 | err = fsm.Trigger(ts.State, "Push", ts)
114 | if err != nil {
115 | t.Errorf("trigger err: %v", err)
116 | }
117 |
118 | lastState := Turnstile{
119 | ID: 1,
120 | EventCount: 6,
121 | CoinCount: 1,
122 | PassCount: 1,
123 | State: "Locked",
124 | States: []string{"Locked", "Unlocked", "Locked"},
125 | }
126 |
127 | if !compareTurnstile(&lastState, ts) {
128 | t.Errorf("Expected last state: %+v, but got %+v", lastState, ts)
129 | } else {
130 | t.Logf("最终的状态: %+v", ts)
131 | }
132 | }
133 |
134 | func compareTurnstile(t1 *Turnstile, t2 *Turnstile) bool {
135 | if t1.ID != t2.ID || t1.CoinCount != t2.CoinCount || t1.EventCount != t2.EventCount || t1.PassCount != t2.PassCount ||
136 | t1.State != t2.State {
137 | return false
138 | }
139 |
140 | return fmt.Sprint(t1.States) == fmt.Sprint(t2.States)
141 | }
142 |
143 | func initFSM() *StateMachine {
144 | delegate := &DefaultDelegate{P: &TurnstileEventProcessor{}}
145 |
146 | transitions := []Transition{
147 | {From: "Locked", Event: "Coin", To: "Unlocked", Action: "check"},
148 | {From: "Locked", Event: "Push", To: "Locked", Action: "invalid-push"},
149 | {From: "Unlocked", Event: "Push", To: "Locked", Action: "pass"},
150 | {From: "Unlocked", Event: "Coin", To: "Unlocked", Action: "repeat-check"},
151 | }
152 |
153 | return NewStateMachine(delegate, transitions...)
154 | }
155 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/smallnest/gofsm
2 |
3 | go 1.12
4 |
--------------------------------------------------------------------------------
/state.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smallnest/gofsm/f5ba1bddca7b9920f23fb34b66440407197e1a2c/state.png
--------------------------------------------------------------------------------