我们可以发现,Door状态只与OnFloor发生关系,Moving状态也只与OnFloor发生关系
我们可以将定两个层级关系的状态来描述这些关系。
builder.In(States.OnFloor) .On(Events.CloseDoor).Goto(States.DoorClosed) .On(Events.OpenDoor).Goto(States.DoorOpen) .On(Events.GoUp) .On(Events.GoDown) builder.In(States.Moving) .On(Events.Stop).Goto(States.OnFloor); builder.In(States.DoorOpen) .ExecuteOnEntry( () => { Said(“正在开门.”); }); builder.In(States.DoorClosed) .ExecuteOnEntry( () => { Said(“正在关门.”); }); //定义层级 builder.DefineHierarchyOn(States.Moving) .WithHistoryType(HistoryType.Shallow) .WithInitialSubState(States.MovingUp) .WithSubState(States.MovingDown); builder.DefineHierarchyOn(States.OnFloor) .WithHistoryType(HistoryType.None) .WithInitialSubState(States.DoorClosed) .WithSubState(States.DoorOpen);History Types:
None: 状态进入初始子状态。子状态本身进入其初始子状态等,直到到达最内层的嵌套状态。. Deep: T状态进入其最后一个活动子状态。子状态本身进入其最后的活跃状态等,直到到达最内层的嵌套状态. Shallow: 状态进入其最后一个活动子状态。子状态本身进入其初始子状态等,直到到达最内层的嵌套状态.比如:
当我们去MovingUp的状态,是先到Moving状态,再到MovingUp状态。
4.0版本,添加在楼层检查超重 builder.In(States.OnFloor) .On(Events.CloseDoor).Goto(States.DoorClosed) .On(Events.OpenDoor).Goto(States.DoorOpen) .On(Events.GoUp) .If(CheckOverload).Goto(States.MovingUp) .Otherwise().Execute(this.AnnounceOverload) .On(Events.GoDown) .If(CheckOverload).Goto(States.MovingDown) .Otherwise().Execute(this.AnnounceOverload); 5.0版本 添加电梯异常状态 builder.DefineHierarchyOn(States.Healthy) .WithHistoryType(HistoryType.Deep) .WithInitialSubState(States.OnFloor) .WithSubState(States.Moving); builder.DefineHierarchyOn(States.Moving) .WithHistoryType(HistoryType.Shallow) .WithInitialSubState(States.MovingUp) .WithSubState(States.MovingDown); builder.DefineHierarchyOn(States.OnFloor) .WithHistoryType(HistoryType.None) .WithInitialSubState(States.DoorClosed) .WithSubState(States.DoorOpen); builder.In(States.Healthy) .On(Events.Error).Goto(States.Error); builder.In(States.Error) .On(Events.Reset).Goto(States.Healthy) .On(Events.Error); builder.In(States.OnFloor) .ExecuteOnEntry(this.AnnounceFloor) .ExecuteOnExit(Beep) .ExecuteOnExit(Beep) // just beep a second time .On(Events.CloseDoor).Goto(States.DoorClosed) .On(Events.OpenDoor).Goto(States.DoorOpen) .On(Events.GoUp) .If(CheckOverload).Goto(States.MovingUp) .Otherwise().Execute(this.AnnounceOverload) .On(Events.GoDown) .If(CheckOverload).Goto(States.MovingDown) .Otherwise().Execute(this.AnnounceOverload); builder.In(States.Moving) .On(Events.Stop).Goto(States.OnFloor);再也不用变量+IF ELSE了,
添加状态和事件就可以了
逻辑也更清晰
Demo
tiancai4652/StateMachineSapmle: appccelerate/statemachine wpf Sample (github.com)