一、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();
}
}
测试
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
设计模式系列博文导航
一、创建型 - 5种
原型模式(Prototype Pattern)
抽象工厂模式(Abstract Factory Pattern)
建造者模式(Builder Pattern)
工厂模式(Factory Pattern)
单例模式(Singleton Pattern)
助记语:原抽建工单
二、结构型 - 8种
享元模式(Flyweight Pattern)
代理模式(Proxy Pattern)
适配器模式(Adapter Pattern)
外观模式(Facade Pattern)
过滤器模式(Filter/Criteria Pattern)
桥接模式(Bridge Pattern)
组合模式(Composite Pattern)
装饰器模式(Decorator Pattern)
助记语:想呆室外,过桥组装
三、行为型 - 11种
责任链模式(Chain of Responsibility Pattern)
命令模式(Command Pattern)
解释器模式(Interpreter Pattern)
中介者模式(Mediator Pattern)
迭代器模式(Iterator Pattern)
观察者模式(Observer Pattern)
策略模式(Strategy Pattern)
状态模式(State Pattern)
备忘录模式(Memento Pattern)
模板方法模式(Template Pattern)
访问者模式(Visitor Pattern)
助记语:责令解中谍,观测状被模仿