Write simples state machine on c sharp programming language with classes
时间: 2024-05-02 13:20:25 浏览: 8
Here is an example of a simple state machine in C# using classes:
```
public class StateMachine
{
private State currentState;
public StateMachine()
{
currentState = new StateA();
}
public void ProcessEvent(Event e)
{
currentState.HandleEvent(this, e);
}
public void ChangeState(State newState)
{
currentState = newState;
}
}
public abstract class State
{
public abstract void HandleEvent(StateMachine machine, Event e);
}
public class StateA : State
{
public override void HandleEvent(StateMachine machine, Event e)
{
if (e is EventX)
{
// Handle Event X
machine.ChangeState(new StateB());
}
else if (e is EventY)
{
// Handle Event Y
}
}
}
public class StateB : State
{
public override void HandleEvent(StateMachine machine, Event e)
{
if (e is EventY)
{
// Handle Event Y
machine.ChangeState(new StateA());
}
else if (e is EventZ)
{
// Handle Event Z
machine.ChangeState(new StateC());
}
}
}
public class StateC : State
{
public override void HandleEvent(StateMachine machine, Event e)
{
if (e is EventX)
{
// Handle Event X
machine.ChangeState(new StateB());
}
}
}
public abstract class Event { }
public class EventX : Event { }
public class EventY : Event { }
public class EventZ : Event { }
```
In this example, we have a `StateMachine` class that maintains the current state and handles events. The state machine transitions between states by calling the `ChangeState` method.
We also have a `State` abstract class that defines the behavior for handling events. Each concrete state class (`StateA`, `StateB`, `StateC`) implements its own behavior for handling events.
Finally, we have some concrete `Event` classes (`EventX`, `EventY`, `EventZ`) that are used to trigger state transitions.
This is just a simple example, and in practice, state machines can be much more complex. However, the basic structure of a state machine using classes should be similar to this.