迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供了一种顺序访问集合对象元素的方法,同时不暴露集合对象的内部表示。迭代器模式的关键是将集合对象的遍历操作从集合类中抽离出来,封装成一个独立的迭代器类,这样可以在不改变集合对象结构的情况下,灵活地遍历集合对象。
迭代器模式主要包含以下几个角色:
- 抽象迭代器(Iterator):定义遍历元素所需的接口,一般包括 hasNext()、next() 等方法;
- 具体迭代器(ConcreteIterator):实现抽象迭代器接口,具体处理遍历过程;
- 抽象集合(Aggregate):定义创建迭代器对象的接口,通常是一个方法,如 createIterator();
- 具体集合(ConcreteAggregate):实现抽象集合接口,返回一个具体迭代器的实例。
我通过一个Java示例进行分析。假设我们需要实现一个书籍列表类,该类可以存储书籍,并按顺序访问所有书籍。
首先,我们需要定义抽象迭代器和抽象集合接口:
// 抽象迭代器接口
public interface Iterator {
boolean hasNext();
Object next();
}
// 抽象集合接口
public interface Aggregate {
Iterator createIterator();
}
接下来,我们实现具体的书籍列表类(ConcreteAggregate)和书籍迭代器类(ConcreteIterator):
// 具体集合类
public class BookList implements Aggregate {
private List<Book> books;
public BookList() {
books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
}
public Book getBookAt(int index) {
return books.get(index);
}
public int getBookCount() {
return books.size();
}
@Override
public Iterator createIterator() {
return new BookListIterator(this);
}
}
// 具体迭代器类
public class BookListIterator implements Iterator {
private BookList bookList;
private int index;
public BookListIterator(BookList bookList) {
this.bookList = bookList;
this.index = 0;
}
@Override
public boolean hasNext() {
return index < bookList.getBookCount();
}
@Override
public Object next() {
return hasNext() ? bookList.getBookAt(index++) : null;
}
}
最后,我们创建一个测试类来测试书籍列表的遍历:
public class IteratorExample {
public static void main(String[] args) {
BookList bookList = new BookList();
bookList.addBook(new Book("Java编程思想", "Zhang San"));
bookList.addBook(new Book("软件构造", "Rainy Wang"));
bookList.addBook(new Book("Java核心技术", "Li si"));
Iterator iterator = bookList.createIterator();
while (iterator.hasNext()) {
Book book = (Book) iterator.next();
System.out.println(book.getName() + " - " + book.getAuthor());
}
}
}
class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
}
通过这个示例,我们可以看到迭代器模式的优点:
- 封装性:迭代器模式将遍历操作与集合对象分离,使得我们可以在不暴露集合对象内部实现的情况下进行遍历;
- 扩展性:当需要对集合对象添加新的遍历方式时,只需增加一个新的迭代器类即可,无需修改集合对象;
- 单一职责:迭代器模式让集合对象和迭代器各自负责各自的职责,符合单一职责原则。