在 设计模式系列之状态模式(3) 中对审批流程进行了介绍。本文简单介绍一下C#的状态机-stateless。
状态机
状态机是一种用来进行对象建模的工具,它是一个有向图形,由一组节点和一组相应的转移函数组成。状态机通过响应一系列事件而“运行”。每个事件都在属于“当前” 节点的转移函数的控制范围内,其中函数的范围是节点的一个子集。函数返回“下一个”(也许是同一个)节点。这些节点中至少有一个必须是终态。当到达终态, 状态机停止。
状态模式主要用来解决对象状态转换比较复杂的情况。它把状态的逻辑判断转移到不同的类中,可以把复杂的逻辑简单化。上图是Java的线程状态切换场景。
要素
状态机有4个要素,即现态、条件、动作、次态。其中,现态和条件是“因”, 动作和次态是“果”。
- 现态 - 是指当前对象的状态
- 条件 - 当一个条件满足时,当前对象会触发一个动作
- 动作 - 条件满足之后,执行的动作
- 次态 - 条件满足之后,当前对象的新状态。次态是相对现态而言的,次态一旦触发,就变成了现态
Stateless
Stateless是一款基于.NET的开源状态机库,最新版本4.4.0, 使用它你可以很轻松的在.NET中创建状态机和以状态机为基础的轻量级工作流。
由于整个项目基于.NET Standard的编写的,所以在.NET Framework和.NET Core项目中都可以使用。
特性
Most standard state machine constructs are supported:
Generic support for states and triggers of any .NET type (numbers, strings, enums, etc.)
- Hierarchical states
- Entry/exit actions for states
- Guard clauses to support conditional transitions
- Introspection
Some useful extensions are also provided:
- Ability to store state externally (for example, in a property tracked by an ORM)
- Parameterised triggers
- Reentrant states
- 支持DOT格式图导出
模拟开关
点击空格可以在on/off之间来回切换,代码如下:
static void Main(string[] args)
{
const string on = "On";
const string off = "Off";
const char space = ' ';
// Instantiate a new state machine in the 'off' state
var onOffSwitch = new StateMachine<string, char>(off);
// Configure state machine with the Configure method, supplying the state to be configured as a parameter
onOffSwitch.Configure(off).Permit(space, on);
onOffSwitch.Configure(on).Permit(space, off);
string graph = UmlDotGraph.Format(onOffSwitch.GetInfo());
Console.WriteLine(graph);
Console.WriteLine("Press <space> to toggle the switch. Any other key will exit the program.");
while (true)
{
Console.WriteLine("Switch is in state: " + onOffSwitch.State);
var pressed = Console.ReadKey(true).KeyChar;
// Check if user wants to exit
if (pressed != space) break;
// Use the Fire method with the trigger as payload to supply the state machine with an event.
// The state machine will react according to its configuration.
onOffSwitch.Fire(pressed);
}
状态切换配置在代码里面已经写的很清楚了。本文主要看DOT格式的语言如何渲染。程序运行结果如下:
其中上半部分对应的代码。
string graph = UmlDotGraph.Format(onOffSwitch.GetInfo());
Console.WriteLine(graph);
The UmlDotGraph.Format() method returns a string representation of the state machine in the DOT graph language。
渲染DOT图像语言
- 下载graphviz,可在官网下载,也可以在UserForPlantUml.msi.zip 中下载。安装过程注意要添加环境变量。
- 新建文件test.dot.写入上面对应的字符串,当然也可以通过程序来完成。
- 终端运行
dot -T pdf -o phoneCall.pdf phoneCall.dot
- 最终生成的pdf
写在最后
这里知识简单介绍下stateless的作用和DOT格式的渲染。后续会基于此完成请假审批流程。
参考
.NET中的状态机库Stateless
公众号