diff --git a/03-behavioral/state/README.md b/03-behavioral/state/README.md new file mode 100644 index 0000000..b481703 --- /dev/null +++ b/03-behavioral/state/README.md @@ -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/ diff --git a/README.md b/README.md index 1ccb34b..8c64bdf 100644 --- a/README.md +++ b/README.md @@ -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