首先附上 示例程序类图:
20190327101750.png
实例源代码:
Aggregate.java
package IteratorPattern;
import java.util.Iterator;
public interface Aggregate {
public abstract Iterator iterator();
}
Book.java
package IteratorPattern;
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
BookShelf.java
package IteratorPattern;
import java.util.Iterator;
public class BookShelf implements Aggregate {
private Book[] books;
private int last = 0;
public BookShelf(int maxsize) {
this.books = new Book[maxsize];
}
public Book getBookAt(int index) {
return books[index];
}
public void appendBook(Book book) {
this.books[last] = book;
last++;
}
public int getLength() {
return last;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
BookShelfIterator.java
package IteratorPattern;
import java.util.Iterator;
public class BookShelfIterator implements Iterator {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
Main.java
package IteratorPattern;
import java.util.Iterator;
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 it = bookShelf.iterator();
while (it.hasNext()) {
Book book = (Book) it.next();
System.out.println(book.getName());
}
}
}
20190327103613.png
20190327103622.png
总结:
因为Iterator 将遍历与实现分离开来.
例如:while (it.hasNext()) {
Book book = (Book) it.next();
System.out.println(book.getName());
}
这段代码中,只是使用了Iterator 的 hasNext() 和next() 方法,并没有调用BookShelf 方法.
设计模式的作用就是帮助我们编写可复用的类。“可复用”就是将类实现为“组件”,当一个组件发生改变时,不需要对其他的组件进行修改或只需很小的修改即可应对。
网友评论