Allow an object to alter its behavior when its internal state changes. Behavior varies based on state. You want to avoid large conditionals. Pros:
State
Overview
Allow an object to alter its behavior when its internal state changes.
When to use
- Behavior varies based on state.
- You want to avoid large conditionals.
Java example
TypeScript example
Pros and cons
Pros:
- Removes complex conditional logic.
- State transitions are explicit.
Cons:
- More classes for each state.
- Can be overkill for simple cases.
Common pitfalls
- States that leak knowledge of others.
- Hidden transitions spread across code.