diff --git a/03-behavioral/iterator/README.md b/03-behavioral/iterator/README.md new file mode 100644 index 0000000..5ae040b --- /dev/null +++ b/03-behavioral/iterator/README.md @@ -0,0 +1,31 @@ +# Iterator Design Pattern — Java Example + +**Pattern:** Behavioral → Iterator +**Article:** https://ankurm.com/iterator-design-pattern-java/ + +## What this example shows + +A `BookShelf` stores `Book` objects in an internal `ArrayList` but never exposes it. Callers only see the `BookIterator` interface (`hasNext()`/`next()`). `BookShelf` hands out two different concrete iterators: `ForwardIterator` walks every book in order, and `DecadeIterator` filters to only books published in a given decade, computing the next match lazily as `advance()` is called. `Main` exercises both iterators, then prints a line noting that `java.util.Iterator`/for-each work the same way under the hood. + +## How to run + +```bash +javac iterator/*.java -d out/iterator +java -cp out/iterator iterator.Main +``` + +Requires Java 25. + +## Post Section ↔ File Mapping + +| Post Section | File(s) | +|---|---| +| Custom Iterator Implementation — the Iterator interface | `BookIterator.java` | +| Custom Iterator Implementation — the element type | `Book.java` | +| Custom Iterator Implementation — the Aggregate (BookShelf, ForwardIterator, DecadeIterator) | `BookShelf.java` | +| Custom Iterator Implementation — wiring it together | `Main.java` | + +Note: the "How Java's For-Each Loop Uses Iterator" snippet (`Iterable` example) is illustrative only — it is not part of this repository's runnable example. + +Article: https://ankurm.com/iterator-design-pattern-java/ +All patterns: https://ankurm.com/design-patterns-java/ diff --git a/README.md b/README.md index 6e5197a..86e6e97 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,23 @@ javac 03-behavioral/command/*.java -d out/command java -cp out/command command.Main ``` +### Iterator (`03-behavioral/iterator/`) + +| Post Section | File(s) | +|---|---| +| Custom Iterator Implementation — the Iterator interface | `BookIterator.java` | +| Custom Iterator Implementation — the element type | `Book.java` | +| Custom Iterator Implementation — the Aggregate (BookShelf, ForwardIterator, DecadeIterator) | `BookShelf.java` | +| Custom Iterator Implementation — wiring it together | `Main.java` | + +Note: the "How Java's For-Each Loop Uses Iterator" snippet (`Iterable` example) is illustrative only — it is not part of this repository's runnable example. + +Run it: +```bash +javac 03-behavioral/iterator/*.java -d out/iterator +java -cp out/iterator iterator.Main +``` + ## Reference - *Design Patterns: Elements of Reusable Object-Oriented Software* — Gamma, Helm, Johnson, Vlissides