1参考文章
参考1:http://topic.csdn.net/u/20080722/16/e7fcffc3-3d54-48f6-9d3a-2cd39073a287.html
参考2:http://www.java63.com/design_pattern/iterator_pattern.html
参考3:http://blog.csdn.net/aaaaaaaa0705/article/details/6282305
想找一些关于迭代器next()和hasNext()方法的内容,最后都归宗到迭代器以及设计模式中的迭代器模式。现在记录一下,有空写一篇学习心得。
Iterator(迭代器接口):该接口必须定义实现迭代功能的最小定义方法集,比如提供hasNext()和next()方法。
ConcreteIterator(迭代器实现类): 比如BookShelfIterator,迭代器接口Iterator的实现类。可以根据具体情况加以实现。
Aggregate(容器接口):定义基本功能以及提供类似Iterator iterator()的方法。
ConcreteAggregate(容器实现类): 比如BookShelf,容器接口的实现类。必须实现Iterator iterator()方法。
public interface Aggregate { public abstract Iterator iterator(); }
public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); }
public class Book { private String name=""; public Book(String name) { this.name = name; } /** * 获得书籍名称 * @return String */ public String getName() { return name; } }
/** * 书架类 * ConcreateAggregate */ 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 books.length; } //获得书架迭代器对象 @Override public Iterator iterator() { return new BookShelfIterator(this); } }
//ConcreateIterator public class BookShelfIterator implements Iterator{ private BookShelf bookShelf; private int index; public BookShelfIterator(BookShelf bookShelf) { this.bookShelf = bookShelf; this.index = 0; } //检查是否还有下一本书 public boolean hasNext() { if(index < bookShelf.getLength()) { return true; } else { return false; } } //返回指定位置的书籍 public Object next() { Book book = bookShelf.getBookAt(index); index ++; return book; } }
public class Main { public static void main(String[] args) { //生成一个书架 BookShelf bookShelf = new BookShelf(4); //向书架添加书籍 bookShelf.appendBook(new Book("周恩来的晚年岁月")); bookShelf.appendBook(new Book("C++网络编程")); bookShelf.appendBook(new Book("J2EE网络编程精解")); bookShelf.appendBook(new Book("Java编程思想")); //获得书架迭代器 Iterator it = bookShelf.iterator(); while(it.hasNext()) { Book book = (Book)it.next(); System.out.println(book.getName()); } } }
总而言之,迭代器设计模式的总体思想就是“在容器实现类中实现对实体的增删改查操作,而在迭代器实现类中实现遍历操作。”