Add all 23 GoF design pattern implementations (2026-06-13)

This commit is contained in:
Ankur
2026-06-13 21:44:56 +05:30
commit a5beb61425
106 changed files with 2977 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
package iterator;
import java.util.ArrayList;
import java.util.List;
/**
* Aggregate — the collection. Exposes iterators without
* revealing its internal storage structure.
*/
public class BookShelf {
private final List<Book> books = new ArrayList<>();
public void addBook(Book book) { books.add(book); }
/** Standard forward iterator */
public BookIterator iterator() {
return new ForwardIterator();
}
/** Filtered iterator — only books from a specific decade */
public BookIterator iteratorByDecade(int decade) {
return new DecadeIterator(decade);
}
// --- Inner iterator implementations ---
private class ForwardIterator implements BookIterator {
private int index = 0;
@Override public boolean hasNext() { return index < books.size(); }
@Override public Book next() { return books.get(index++); }
}
private class DecadeIterator implements BookIterator {
private final int decade;
private int index = 0;
private Book nextBook;
DecadeIterator(int decade) {
this.decade = decade;
advance();
}
private void advance() {
nextBook = null;
while (index < books.size()) {
Book b = books.get(index++);
if (b.getYear() / 10 * 10 == decade) { nextBook = b; break; }
}
}
@Override public boolean hasNext() { return nextBook != null; }
@Override public Book next() {
Book b = nextBook; advance(); return b;
}
}
}