Files
design-patterns/03-behavioral/strategy/README.md

34 lines
1.6 KiB
Markdown

# 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/