State: sync post code blocks to repo exactly, split merged Red/Green/YellowState block, Java 25, H6 file labels, fix stale console output, README mapping

This commit is contained in:
2026-06-24 17:26:06 +05:30
parent 03c93b5037
commit 09a7b69d89
2 changed files with 52 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
# 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/

View File

@@ -407,6 +407,25 @@ javac 03-behavioral/observer/*.java -d out/observer
java -cp out/observer observer.Main
```
### State (`03-behavioral/state/`)
| 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 is illustrative only — it is not part of this repository's runnable example.
Run it:
```bash
javac 03-behavioral/state/*.java -d out/state
java -cp out/state state.Main
```
## Reference
- *Design Patterns: Elements of Reusable Object-Oriented Software* — Gamma, Helm, Johnson, Vlissides