我有一些相当简单的状态需求(目前)。我想我想使用Stateless api对这些进行建模。 (但我对状态机并不是很了解,所以我错了。)
但是我会被术语所吸引(特别是州和触发)
这是一个例子:我有一个订单类。它设置有几个状态。它们是:新的,填充的,装运的,已完成的,已取消的。
我想要的一些简单的状态规则是允许这些状态转换:
所以我在这里被绊倒的是我的“触发器”是什么?
如果需要更具体的示例,请说我想要一个这样的方法:
public bool UpdateOrderStatus(int OrderId, OrderStatusEnum NewOrderStatus)
如果状态更新成功,则返回true。如何设置和使用Stateless来实现这一目标?
答案 0 :(得分:27)
机器一次只能处于一种状态;它处于任何状态 给定时间称为当前状态。它可以从一个州改变 当由触发事件或条件启动时,这是另一个 称为过渡。 from Finite-state machine on 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);