设计模式之迭代器
Iterator Pattern 是指依序遍历并处理多个数字或变量,Iterate英文单字本身也是“反复”的意思,Iterator这个名词可译为"迭代器"(书本原文)
代码如下:
代码如下:
- /**
- * 程序主类
- * DemoTest.java
- */
- public class DemoTest {
- /**
- * @param args
- */
- 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());
- }
- }
- }
- /**
- * 聚合接口
- * Aggregate.java
- *
- */
- public interface Aggregate {
- public abstract Iterator iterator();
- }
- /**
- * 迭代接口
- * Iterator.java
- */
- public interface Iterator {
- public abstract boolean hasNext();
- public abstract Object next();
- }
- /**
- * 书架迭代者
- * BookShelfIterator.java
- */
- public class BookShelfIterator implements Iterator {
- private BookShelf bookShelf;
- private int index;
- /**
- * 构造方法
- * @param bookShelft 书架对象
- */
- 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;
- }
- }
- /**
- * 书架类
- * BookShelf.java
- */
- public class BookShelf implements Aggregate {
- private Book[] books;
- private int last = 0;
- /**
- * 构造方法
- * @param maxSize 书架的最大藏书量
- */
- public BookShelf(int maxSize) {
- this.books = new Book[maxSize];
- }
- /**
- * 获得书本对象
- * @param index 书本在书架的索引值
- * @return 书对对象的引用
- */
- public Book getBook(int index) {
- return books[index];
- }
- /**
- * 向书架添加书本
- * @param book 添加的书本对象
- */
- public void appendBook(Book book) {
- books[last] = book;
- last++;
- }
- /**
- * 获得书架中书本的个数
- * @return 书本的个数
- */
- public int getLength() {
- return last;
- }
- /**
- * 迭代方法
- */
- public Iterator iterator() {
- return new BookShelfIterator(this);
- }
- }
- /**
- * 书本类
- * Book.java
- */
- public class Book {
- private String name = "";
- /**
- * 构造方法
- * @param name 书名
- */
- public Book(String name) {
- this.name = name;
- }
- /**
- * 获得书本书名的方法
- * @return 书名
- */
- public String getName() {
- return name;
- }
- }