State allows an object to change its behavior when its internal state changes, appearing to change its class.
- Removes complex state conditionals
- Improves readability & scalability
C Example
#include <stdio.h>
void idleState() { printf("Idle\n"); }
void runState() { printf("Running\n"); }
typedef void (*State)();
int main() {
State current = idleState;
current();
current = runState;
current();
}
C++ Example
#include <iostream>
using namespace std;
class State {
public:
virtual void handle() = 0;
};
class Idle : public State {
public:
void handle() override { cout << "Idle\n"; }
};
class Running : public State {
public:
void handle() override { cout << "Running\n"; }
};
class Machine {
State* state;
public:
void setState(State* s){ state = s; }
void run(){ state->handle(); }
};
int main() {
Machine m;
Idle idle; Running run;
m.setState(&idle);
m.run();
m.setState(&run);
m.run();
}