Files

38 lines
1.6 KiB
Java

package iterator;
/**
* Iterator Design Pattern — Runnable Demo
* Run: javac iterator/*.java -d out/iterator && java -cp out/iterator iterator.Main
* Article: https://ankurm.com/iterator-design-pattern-java/
*/
public class Main {
public static void main(String[] args) {
System.out.println("=== Iterator Design Pattern Demo ===\n");
BookShelf shelf = new BookShelf();
shelf.addBook(new Book("Clean Code", "Robert Martin", 2008));
shelf.addBook(new Book("The Pragmatic Programmer","Andrew Hunt", 1999));
shelf.addBook(new Book("Effective Java", "Joshua Bloch", 2001));
shelf.addBook(new Book("Design Patterns", "Gang of Four", 1994));
shelf.addBook(new Book("Refactoring", "Martin Fowler", 2018));
shelf.addBook(new Book("Working Effectively with Legacy Code", "Michael Feathers", 2004));
System.out.println("-- All books (forward iterator) --");
BookIterator it = shelf.iterator();
while (it.hasNext()) {
System.out.println(" " + it.next());
}
System.out.println("\n-- Books from the 2000s --");
BookIterator it2000s = shelf.iteratorByDecade(2000);
while (it2000s.hasNext()) {
System.out.println(" " + it2000s.next());
}
System.out.println("\n-- JDK Iterable: same pattern, different vocabulary --");
System.out.println(" java.util.Iterator is our BookIterator; for-each uses it under the hood");
System.out.println("\n=== Demo complete ===");
}
}