-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachine.cs
More file actions
51 lines (48 loc) · 1.34 KB
/
StateMachine.cs
File metadata and controls
51 lines (48 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestGround
{
public enum State
{
SwitchOn,
EnterMoney,
DispenseCandy,
SwitchOff
}
public enum Trigger
{
CoinInserted,
ButtonPressed,
CandyDispensed,
}
public class StateMachine<TState,TTrigger>
{
private readonly Dictionary<(TState, TTrigger), TState> _transitions;
public TState CurrentState { get; private set; }
public StateMachine(TState initialState)
{
CurrentState = initialState;
_transitions = new Dictionary<(TState, TTrigger), TState>();
}
public void AddTransition(TState from, TTrigger trigger, TState to)
{
_transitions[(from, trigger)] = to;
}
public void Fire(TTrigger trigger)
{
var key = (CurrentState, trigger);
if (_transitions.TryGetValue(key, out var nextState))
{
CurrentState = nextState;
}
else
{
throw new InvalidOperationException($"No transition defined for {CurrentState} on {trigger}");
}
}
}
}