将for循环中的变量i的作用抽象化、通用化后形成的模式被称为Iterator模式。用于在数据集合中按照顺序遍历集合。
实例程序:
Aggregate接口:
Aggregate接口是所要遍历的集合的接口。实现了该接口的类将成为一个可以保存多个元素的集合,就像数组一样。
| 名字 | 说明 |
|---|---|
| Aggregate | 表示集合的接口 |
| Iterator | 遍历集合的接口 |
| Book | 表示书的类 |
| BookShelf | 表示书架的类 |
| BookShelfIterator | 遍历书架的类 |
| Main | 测试程序行为的类 |
public interface Aggregate {public abstract Iterator iterator();}
Iterator接口:
Iterator接口用于遍历集合中的元素,其作用相当于循环语句中的循环变量。
public interface Iterator {public abstract boolean hasNext();public abstract Object next();}
这边声明了两个方法,即判断是否存在下一个元素的hasNext方法,和获取下一个元素的next方法。hasNext方法的返回值是boolean类型的。
Book类:
public class Book {private String name;public Book(String name) {this.name = name;}public String getName() {return name;}}
BoolShelf类
BookShelf代表书架。
public class BookShelf implements Aggregate {private Book[] books;private int last = 0;public BookShelf(int maxSize) {this.books = new Book[maxSize];}public Book getBookByIndex(int index) {return books[index];}public void appendBook(Book book) {this.books[last] = book;last++;}public int getLength() {return last;}@Overridepublic Iterator iterator() {return new BookShelfIterator(this);}}
BookShelfIterator类:
public class BookShelfIterator implements Iterator {private BookShelf bookShelf;private int index;public BookShelfIterator(BookShelf bookShelf) {this.bookShelf = bookShelf;this.index = 0;}@Overridepublic boolean hasNext() {if (index< bookShelf.getLength()) {return true;}else {return false;}}@Overridepublic Object next() {Book book = bookShelf.getBookByIndex(index);index++;return book;}}
Main
public class Main {public static void main(String[] args) {BookShelf bookShelf = new BookShelf(4);bookShelf.appendBook(new Book("Around the World in 80 Days"));bookShelf.appendBook(new Book("Bible"));bookShelf.appendBook(new Book("Cinderella"));bookShelf.appendBook(new Book("Daddy-Long_Legs"));Iterator iterator = bookShelf.iterator();while (iterator.hasNext()){Book book = (Book) iterator.next();System.out.println(book.getName());}}}
拓展思路的要点:
不管实现如何变化,都可以使用Iterator:
为什么一定要考虑引入Iterator这种复杂的设计模式呢?如果是数组,直接使用for循环语句进行循环处理不可以么?为什么需要将遍历与实现分离开呢?
因为这样迭代器不依赖于BookShelf的实现。如果编写BookShelf的开发人员决定放弃用数组来管理书本,不管BookShelf如何变化,只要BookShelf的iterator方法能正确地返回Iteerator的实例(hasNext和next方法都可以正常工作),即使不对上面的while循环做任何修改,代码都可以正常工作。
这对于BookShelf的调用者来说特别方便,设计模式的作用就是帮助编写出可复用的类。所谓的可复用,就是指将类实现为“组件”,当一个组件发生变化时,不需要对其它的组件进行修改或是只需要很小的修改即可应对。
难以理解抽象类和接口:
一般人都喜欢使用具体的类来解决问题,很容易导致类之间的强耦合,这些类也难以作为组件被再次利用,为什么弱化类之间的耦合,进而使用类更加容易作为组件被再次利用,我们需要引入抽象类和接口。
所以不要只使用具体类来编程,要优先使用抽象类和接口来编程。
