State Machine Patterns
Transition Table
A transition table stores the next state for each state and event pair.
Transition Table
transition_table.c
#include <stdio.h>
enum DoorState {
DOOR_CLOSED,
DOOR_OPEN,
DOOR_LOCKED
};
enum DoorEvent {
EVENT_OPEN,
EVENT_CLOSE,
EVENT_LOCK
};
int main(void) {
int event = ;
int table[3][3] = {
{DOOR_OPEN, DOOR_CLOSED, DOOR_LOCKED},
{DOOR_OPEN, DOOR_CLOSED, DOOR_OPEN},
{DOOR_LOCKED, DOOR_LOCKED, DOOR_LOCKED}
};
enum DoorState state = DOOR_CLOSED;
state = (enum DoorState)table[state][event];
printf("event=%d state=%d\n", event, state);
return 0;
}
#include <stdio.h>
enum DoorState {
DOOR_CLOSED,
DOOR_OPEN,
DOOR_LOCKED
};
enum DoorEvent {
EVENT_OPEN,
EVENT_CLOSE,
EVENT_LOCK
};
int main(void) {
int event = ;
int table[3][3] = {
{DOOR_OPEN, DOOR_CLOSED, DOOR_LOCKED},
{DOOR_OPEN, DOOR_CLOSED, DOOR_OPEN},
{DOOR_LOCKED, DOOR_LOCKED, DOOR_LOCKED}
};
enum DoorState state = DOOR_CLOSED;
state = (enum DoorState)table[state][event];
printf("event=%d state=%d\n", event, state);
return 0;
}
#include <stdio.h>
enum DoorState {
DOOR_CLOSED,
DOOR_OPEN,
DOOR_LOCKED
};
enum DoorEvent {
EVENT_OPEN,
EVENT_CLOSE,
EVENT_LOCK
};
int main(void) {
int event = ;
int table[3][3] = {
{DOOR_OPEN, DOOR_CLOSED, DOOR_LOCKED},
{DOOR_OPEN, DOOR_CLOSED, DOOR_OPEN},
{DOOR_LOCKED, DOOR_LOCKED, DOOR_LOCKED}
};
enum DoorState state = DOOR_CLOSED;
state = (enum DoorState)table[state][event];
printf("event=%d state=%d\n", event, state);
return 0;
}
table
Rows represent current states and columns represent events.
lookup
One table lookup replaces a chain of repeated branch checks.