1. Iterator模式
Iterator模式用于在数据集合中按照顺序遍历集合。将遍历与实现分离。
1.1 Iterator模式的类图
角色:
- Iterator(迭代器)
定义按顺序逐个遍历元素的接口(API) - ConcreteIterator(具体的迭代器)
实现Iterator角色定义的接口(API) - Iterable(可迭代的集合)
定义创建Iterator角色的接口(API) - ConcreteIterable(具体的可迭代的集合)
实现Iterable所定义的接口
1.2 示例程序
类和接口一览表
名字 | 说明 |
---|---|
Iterable | 可遍历集合的接口 |
Iterator | 遍历集合的接口 |
Book | 表示书的类 |
BookShelf | 表示书架的类 |
BookShelfIterator | 遍历书架的类 |
说明:这里将BookShelfIterator迭代器类作为内部类(默认你已经理解内部类了)放在BookShelf中,也是和jdk的集合类的设计类似。
只显示继承,内部类关系的图:
显示依赖关系的类图,idea的uml图显示的稍微有点杂,抓住主要的看:
Iterator接口
package xin.ajay.framework;
public interface Iterator {
//是否存在下一个元素
boolean hasNext();
//获取下一个元素
Object next();
}
Iterable接口
package xin.ajay.framework;
public interface Iterable{
//创建迭代器
Iterator iterator();
}
Book类
package xin.ajay.impl;
public class Book {
private String name;
public Book(String name){
this.name = name;
}
public String getName() {
return name;
}
}
BookShelf及其内部类BookShelfIterator
package xin.ajay.impl;
import xin.ajay.framework.Iterable;
import xin.ajay.framework.Iterator;
public class BookShelf implements Iterable {
private Book[] books;
private int last;
public BookShelf(int size) {
this.books = new Book[size];
}
public Book getBook(int index){
return books[index];
}
public void addBook(Book book){
this.books[last] = book;
last++;
}
public int getLength(){
return last;
}
@Override
public Iterator iterator() {
return new BookShelfIterator();
}
//迭代器类
private class BookShelfIterator implements Iterator{
private int index;
@Override
public boolean hasNext() {
return index < last;
}
@Override
public Object next() {
Book book = books[index];
index++;
return book;
}
}
//测试执行
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(4);
bookShelf.addBook(new Book("A"));
bookShelf.addBook(new Book("B"));
bookShelf.addBook(new Book("C"));
bookShelf.addBook(new Book("D"));
Iterator iterator = bookShelf.iterator();
while (iterator.hasNext()){
Book book = (Book) iterator.next();
System.out.println(book);
}
}
}
鸣谢:
GoF《设计模式》和结城浩的《图解设计模式》