https://github.com/brandonc/statemachine
A simple, templated state machine class for .net
https://github.com/brandonc/statemachine
Last synced: about 1 month ago
JSON representation
A simple, templated state machine class for .net
- Host: GitHub
- URL: https://github.com/brandonc/statemachine
- Owner: brandonc
- License: other
- Created: 2011-06-15T08:53:21.000Z (almost 14 years ago)
- Default Branch: master
- Last Pushed: 2011-06-17T23:36:19.000Z (almost 14 years ago)
- Last Synced: 2025-03-26T13:21:33.727Z (about 2 months ago)
- Language: C#
- Homepage:
- Size: 98.6 KB
- Stars: 12
- Watchers: 3
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# statemachine
> A simple, templated state machine class for c#
## Example ##
public enum OrderState
{
Created,
Ordered,
Cancelled,
Preparing,
Shipped
};public class Order
{
public StateMachine Status { get; set; }public void Complete()
{
this.Status.State = OrderState.Ordered;
}public void Cancel()
{
this.Status.State = OrderState.Cancelled;
}public void Prepare()
{
this.Status.State = OrderState.Preparing;
}public void Ship()
{
this.Status.State = OrderState.Shipped;
}public Order()
{
// You could also subclass StateMachine and encapsulate these details
Status = new StateMachine(OrderState.Created);
// Only transitions defined here are valid. Alternatively, you could call
// ValidAny() to allow all state transitions
Status.Valid(OrderState.Created, OrderState.Ordered);
Status.Valid(OrderState.Ordered, new[] { OrderState.Cancelled, OrderState.Preparing });
Status.Valid(OrderState.Preparing, OrderState.Shipped);// Enter transition events
Status.DoWhenAny((status) =>
{
// Useful for writing a transition history log
Debug.WriteLine("[{0}] Order Status => {1}", (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds, status);
});// Or DoFollowingAny() for exit transitions
}
}## Dynamic Events ##
If you're using .net 4.0, you can use dynamic binding in the style of rails:Status.Transitions.Enter_Shipped((Action)delegate()
{
Debug.WriteLine("Order Shipped!");
});Status.Transitions.Exit_Ordered((Action)delegate()
{
Debug.WriteLine("Order Processed!");
});