機器一次只處於一種狀態;它在任何時間的狀態 被稱爲當前狀態。當由觸發事件或條件啓動時,它可以從一個狀態 變爲另一個狀態,這是 稱爲轉換。 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
}
Order類:
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 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);
感謝您挖掘無狀態,我之前沒有見過。 – kenny 2012-02-02 18:48:47