# 状态模式
TIP
TODO
状态模式(State):当一个对象的内部状态发生改变时,会导致其行为的改变,这看起来像是改变了对象。
# 有限状态机
有限状态机(Finite-State-Machine)
是游戏中非常常用的一种设计模式
。
不过不止游戏,它在 AI 和编译器程序方面很出名。
有限状态机是一个数学模型,用来表示有限个状态以及这些状态之间的过渡。
- 状态是有限的
- 任一时刻,只处于一种状态中
- 某种条件下,从一种状态转变为另一种状态
包含完整动作信息的有限状态机定义可以使用状态表来表示,比如下表
状态 A | 状态 B | 状态 C | |
---|---|---|---|
条件 X | ... | ... | ... |
条件 Y | 状态 C | ||
条件 Z |
# 简单实践
var StateMachine = require("javascript-state-machine");
var fsm = new StateMachine({
init: "wait", // wait trial 提示 auth 授权 exprie 过期 success 成功 failed 失败
transitions: [
// 试用
{ name: "openTrial", from: "wait", to: "trail" },
{ name: "trial2Wait", from: "trail", to: "wait" },
{ name: "trial2Auth", from: "trial", to: "auth" },
// 授权
{ name: "openAuth", from: "wait", to: "auth" },
{ name: "auth2Success", from: "auth", to: "success" },
{ name: "auth2Failed", from: "auth", to: "failed" },
// 结果
{ name: "success2Wait", from: "success", to: "wait" },
{ name: "failed2Auth", from: "failed", to: "auth" },
{ name: "failed2Wait", from: "failed", to: "wait" },
// 过期 授权
{ name: "openExpire", from: "wait", to: "expire" },
{ name: "expire2Success", from: "expire", to: "success" },
{ name: "expire2Failed", from: "expire", to: "failed" },
// 结果
{ name: "failed2Expire", from: "failed", to: "expire" }
],
methods: {}
});