机器一次只处于一种状态;它在任何给定时间所处的状态称为当前状态。当由触发事件或条件启动时,它可以从一种状态更改为另一种状态,这称为转换。
来自 Wiki 上的有限状态机
我相信,触发器就是这个触发事件。
更新:
当然触发器名称有时可以等于某些状态名称。
New (initial state)
New -> Filled (trigger "Filled")
New -> Cancelled (trigger "Cancelled")
Filled -> Shipping (trigger "ToBeShipped")
Filled -> Cancelled (trigger "Cancelled")
Shipping -> Complete (trigger "Completed").
更新:
无状态是非常好的框架!我试图实现该功能。
状态:
public enum State
{
New,
Filled,
Shipping,
Cancelled,
Completed
}
触发器:
public enum Trigger
{
Filled,
Cancelled,
ToBeShipped,
Completed
}
订单类别:
public class Order
{
private readonly StateMachine<State, Trigger> _stateMachine;
public Order()
{
_stateMachine = CreateStateMachine();
}
public bool TryUpdateOrderStatus(Trigger trigger)
{
if (!_stateMachine.CanFire(trigger))
return false;
_stateMachine.Fire(trigger);
return true;
}
public State Status
{
get
{
return _stateMachine.State;
}
}
private StateMachine<State, Trigger> CreateStateMachine()
{
StateMachine<State, Trigger> stateMachine = new StateMachine<State, Trigger>(State.New);
stateMachine.Configure(State.New)
.Permit(Trigger.Filled, State.Filled)
.Permit(Trigger.Cancelled, State.Cancelled);
stateMachine.Configure(State.Filled)
.Permit(Trigger.ToBeShipped, State.Shipping)
.Permit(Trigger.Cancelled, State.Cancelled);
stateMachine.Configure(State.Shipping)
.Permit(Trigger.Completed, State.Completed);
stateMachine.OnUnhandledTrigger((state, trigger) =>
{
Console.WriteLine("Unhandled: '{0}' state, '{1}' trigger!");
});
return stateMachine;
}
}
订单类测试器:
Order order = new Order();
bool result = order.TryUpdateOrderStatus(Trigger.Completed);
Console.WriteLine("Attemp to complete order: {0}", result);
Console.WriteLine("Order status: {0}", order.Status);
result = order.TryUpdateOrderStatus(Trigger.ToBeShipped);
Console.WriteLine("Attemp to ship order: {0}", result);
Console.WriteLine("Order status: {0}", order.Status);
result = order.TryUpdateOrderStatus(Trigger.Cancelled);
Console.WriteLine("Attemp to cancel order: {0}", result);
Console.WriteLine("Order status: {0}", order.Status);