34 lines
1.6 KiB
Markdown
34 lines
1.6 KiB
Markdown
# State Design Pattern — Java Example
|
|
|
|
**Pattern:** Behavioral → State
|
|
**Article:** https://ankurm.com/state-design-pattern-java/
|
|
|
|
## What this example shows
|
|
|
|
A traffic light with zero if-else state machines. `TrafficLightState` declares what every state must do: handle entry (`onEnter`), handle the transition trigger (`next`), and report its own color. `TrafficLight` is the context — it holds a reference to the current state and delegates every call to it. `RedState`, `GreenState`, and `YellowState` each know only their own entry message and their own next state (Red→Green→Yellow→Red); none of them knows about the full cycle. `Main` creates the light, cycles through six transitions, and prints why this beats a single class full of if-else branches.
|
|
|
|
## How to run
|
|
|
|
```bash
|
|
javac state/*.java -d out/state
|
|
java -cp out/state state.Main
|
|
```
|
|
|
|
Requires Java 25.
|
|
|
|
## Post Section ↔ File Mapping
|
|
|
|
| Post Section | File(s) |
|
|
|---|---|
|
|
| With State: Traffic Light — the State interface | `TrafficLightState.java` |
|
|
| With State: Traffic Light — the Context | `TrafficLight.java` |
|
|
| With State: Traffic Light — RedState | `RedState.java` |
|
|
| With State: Traffic Light — GreenState | `GreenState.java` |
|
|
| With State: Traffic Light — YellowState | `YellowState.java` |
|
|
| With State: Traffic Light — wiring it together | `Main.java` |
|
|
|
|
Note: the "Without State: The if-else Machine" snippet (the fragile `TrafficLight` with a `String state` field) is illustrative only — it is not part of this repository's runnable example.
|
|
|
|
Article: https://ankurm.com/state-design-pattern-java/
|
|
All patterns: https://ankurm.com/design-patterns-java/
|