diff --git a/03-behavioral/strategy/README.md b/03-behavioral/strategy/README.md new file mode 100644 index 0000000..ba540ca --- /dev/null +++ b/03-behavioral/strategy/README.md @@ -0,0 +1,33 @@ +# Strategy Design Pattern — Java Example + +**Pattern:** Behavioral → Strategy +**Article:** https://ankurm.com/strategy-design-pattern-java/ + +## What this example shows + +Three sorting algorithms behind one interface, swappable at runtime. `SortStrategy` declares `sort()` and `getName()`. `BubbleSort`, `MergeSort`, and `QuickSort` each implement the full algorithm — not stubs, the real divide-and-conquer and partition logic. `Sorter` is the context: it holds whichever strategy is active and copies the input array before sorting so callers can compare results without mutating their data. `Main` sorts the same array with all three strategies in turn, then simulates choosing a strategy based on input size. + +## How to run + +```bash +javac strategy/*.java -d out/strategy +java -cp out/strategy strategy.Main +``` + +Requires Java 25. + +## Post Section ↔ File Mapping + +| Post Section | File(s) | +|---|---| +| Implementation: Pluggable Sorting — the Strategy interface | `SortStrategy.java` | +| Implementation: Pluggable Sorting — BubbleSort | `BubbleSort.java` | +| Implementation: Pluggable Sorting — MergeSort | `MergeSort.java` | +| Implementation: Pluggable Sorting — QuickSort | `QuickSort.java` | +| Implementation: Pluggable Sorting — the Context (Sorter) | `Sorter.java` | +| Implementation: Pluggable Sorting — wiring it together | `Main.java` | + +Note: the "Strategy in Java 8+: Lambdas as Strategies" snippet (`Comparator`/lambda example) is illustrative only — it is not part of this repository's runnable example. + +Article: https://ankurm.com/strategy-design-pattern-java/ +All patterns: https://ankurm.com/design-patterns-java/ diff --git a/README.md b/README.md index 8c64bdf..cad3694 100644 --- a/README.md +++ b/README.md @@ -426,6 +426,25 @@ javac 03-behavioral/state/*.java -d out/state java -cp out/state state.Main ``` +### Strategy (`03-behavioral/strategy/`) + +| Post Section | File(s) | +|---|---| +| Implementation: Pluggable Sorting — the Strategy interface | `SortStrategy.java` | +| Implementation: Pluggable Sorting — BubbleSort | `BubbleSort.java` | +| Implementation: Pluggable Sorting — MergeSort | `MergeSort.java` | +| Implementation: Pluggable Sorting — QuickSort | `QuickSort.java` | +| Implementation: Pluggable Sorting — the Context (Sorter) | `Sorter.java` | +| Implementation: Pluggable Sorting — wiring it together | `Main.java` | + +Note: the "Strategy in Java 8+: Lambdas as Strategies" snippet is illustrative only — it is not part of this repository's runnable example. + +Run it: +```bash +javac 03-behavioral/strategy/*.java -d out/strategy +java -cp out/strategy strategy.Main +``` + ## Reference - *Design Patterns: Elements of Reusable Object-Oriented Software* — Gamma, Helm, Johnson, Vlissides