state machine in csharp

A state machine is a behavioral design pattern that can be used to model the behavior of an object or a system. In C#, it can be implemented using a combination of classes and interfaces.

Here's an example of how you can implement a simple state machine in C#:

main.cs
// Define the states
public interface IState
{
    void Handle(Context context);
}

public class StateA : IState
{
    public void Handle(Context context)
    {
        // Handle the state transition to state B
        context.State = new StateB();
    }

    public override string ToString()
    {
        return "State A";
    }
}

public class StateB : IState
{
    public void Handle(Context context)
    {
        // Handle the state transition to state C
        context.State = new StateC();
    }

    public override string ToString()
    {
        return "State B";
    }
}

public class StateC : IState
{
    public void Handle(Context context)
    {
        // Handle the state transition to state A
        context.State = new StateA();
    }

    public override string ToString()
    {
        return "State C";
    }
}

// Define the context
public class Context
{
    public IState State { get; set; }

    public Context()
    {
        State = new StateA();
    }

    public void Request()
    {
        // Defer handling to the current state
        State.Handle(this);
    }
}

// Usage
var context = new Context();
context.Request(); // Current state: State B
context.Request(); // Current state: State C
context.Request(); // Current state: State A
1274 chars
71 lines

In this example, IState represents the interface for a state that handles the context's Handle method. StateA, StateB, and StateC classes implement the IState interface and handle state transitions. Context class represents the object that needs to switch between states, and it keeps track of the current state through the State property. Finally, Request method is the event that triggers the state transition, and the current state is handled appropriately.

gistlibby LogSnag