本文共 2159 字,大约阅读时间需要 7 分钟。
设计模式之迭代器 Iterator Pattern 是指依序遍历并处理多个数字或变量,Iterate英文单字本身也是“反复”的意思,Iterator这个名词可译为"迭代器"(书本原文)
代码如下: - public class DemoTest {
-
- public static void main(String[] args) {
- BookShelf bookShelf = new BookShelf(4);
- bookShelf.appendBook(new Book("Java core1"));
- bookShelf.appendBook(new Book("Java core2"));
- bookShelf.appendBook(new Book("Java core3"));
- bookShelf.appendBook(new Book("Java core4"));
-
-
- Iterator iterator = bookShelf.iterator();
- while(iterator.hasNext()) {
- Book book = (Book)iterator.next();
- System.out.println(" " + book.getName());
- }
- }
- }
- public interface Aggregate {
- public abstract Iterator iterator();
- }
- public interface Iterator {
- public abstract boolean hasNext();
- public abstract Object next();
- }
- public class BookShelfIterator implements Iterator {
- private BookShelf bookShelf;
- private int index;
-
-
- public BookShelfIterator(BookShelf bookShelft) {
- this.bookShelf = bookShelft;
- this.index = 0;
- }
-
-
- public boolean hasNext() {
- if (index < bookShelf.getLength()) {
- return true;
- }else {
- return false;
- }
- }
-
-
- public Object next() {
- Book book = (Book)bookShelf.getBook(index);
- index++;
- return book;
- }
-
-
- }
- public class BookShelf implements Aggregate {
- private Book[] books;
- private int last = 0;
-
-
- public BookShelf(int maxSize) {
- this.books = new Book[maxSize];
- }
-
-
- public Book getBook(int index) {
- return books[index];
- }
-
-
- public void appendBook(Book book) {
- books[last] = book;
- last++;
- }
-
-
- public int getLength() {
- return last;
- }
-
-
- public Iterator iterator() {
- return new BookShelfIterator(this);
- }
-
-
- }
- public class Book {
- private String name = "";
-
- public Book(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
- }
转载地址:http://ofmbi.baihongyu.com/