一、UML类图
二、代码示例
Container角色
public interface BookCollection extends Iterable<Book> {
Iterator<Book> iterator();
}
Container具体类
public class BookLibrary implements BookCollection {
private Collection<Book> books;
public BookLibrary(Collection<Book> books) {
this.books = books;
}
public boolean addBook(Book book) {
return books.add(book);
}
public Collection<Book> getBooks() {
return books;
}
public Iterator<Book> iterator() {
return books.iterator();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
测试
public class Client {
public static void main(String[] args) {
Book[] books = new Book[5];
books[0] = new Book("English", "Head First Java, 2nd Edition", "Kathy Sierra", 10123758943l, 10.5d);
books[1] = new Book("English", "Effective Java (3rd Edition)", "Bloch Joshua", 34422235432l, 8.65d);
books[2] = new Book("English", "Mastering Java Machine Learning", "Dr Uday Kamath", 2123765476l, 21.45d);
books[3] = new Book("English", "Cloud-Native Java", "Kenny Bastani ", 21332343434l, 28.99d);
books[4] = new Book("English", "Java 9 Modularity", "Paul Bakker", 1645243587l, 36.68d);
BookLibrary bookLibrary = new BookLibrary(Arrays.asList(books));
for (Book book : bookLibrary) {
System.out.println(book);
}
}
}
运行结果
Book{language='English', title='Head First Java, 2nd Edition', author='Kathy Sierra', ISBN=10123758943, price=10.5}
Book{language='English', title='Effective Java (3rd Edition)', author='Bloch Joshua', ISBN=34422235432, price=8.65}
Book{language='English', title='Mastering Java Machine Learning', author='Dr Uday Kamath', ISBN=2123765476, price=21.45}
Book{language='English', title='Cloud-Native Java', author='Kenny Bastani ', ISBN=21332343434, price=28.99}
Book{language='English', title='Java 9 Modularity', author='Paul Bakker', ISBN=1645243587, price=36.68}
Process finished with exit code 0
三、参考
- https://www.runoob.com/design-pattern/iterator-pattern.html
- https://www.geeksforgeeks.org/design-patterns-in-java-iterator-pattern/
- https://www.digitalocean.com/community/tutorials/iterator-design-pattern-java