state
Allow an object to alter its behaviour when its internal state changes — the object will appear to change its class.
Files1
View on GitHubSKILL.mdskills/code-quality/state/SKILL.md
GitHubState
Encapsulates each state in its own class. The context delegates behaviour to the current state object instead of using a large conditional.
When to Use
- An object behaves differently depending on its current state
- State-specific behaviour would otherwise require large
if/switchblocks - Transitions between states need to be made explicit and maintainable
- Finite state machines (order status, document workflow, connection lifecycle)
How to Apply
- Define a
Stateinterface with methods for each state-dependent behaviour - Create a concrete state class for each possible state
- The
Contextclass holds a reference to the currentStateand delegates calls to it - States may trigger transitions by calling
context.setState(newState)
Example
interface TrafficLightState { next(ctx: TrafficLight): void; color(): string; }
class RedState implements TrafficLightState {
color() { return 'RED'; }
next(ctx: TrafficLight) { ctx.setState(new GreenState()); }
}
class GreenState implements TrafficLightState {
color() { return 'GREEN'; }
next(ctx: TrafficLight) { ctx.setState(new YellowState()); }
}
class YellowState implements TrafficLightState {
color() { return 'YELLOW'; }
next(ctx: TrafficLight) { ctx.setState(new RedState()); }
}
class TrafficLight {
private state: TrafficLightState = new RedState();
setState(s: TrafficLightState) { this.state = s; }
next() { this.state.next(this); }
color() { return this.state.color(); }
}
const light = new TrafficLight();
console.log(light.color()); // RED
light.next();
console.log(light.color()); // GREEN