首页 > 代码库 > 迭代器模式
迭代器模式
集合类中包含很多数据结构:数组、散列表、ArrayList等,这些集合类的迭代方法都不一样。为了隐藏迭代的具体实现 ,抽象集合类中引用抽象迭代器,具体的集合类引用具体的迭代类,在具体迭代类实现便利具体集合类的方法
package iterator; import java.util.Iterator; /** * 抽象集合类,引用抽象迭代类 */ public interface Aggregate { public abstract Iterator iterator(); }
package iterator; /** * Created by marcopan on 17/4/7. */ public class Book { private String name; public Book(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package iterator; import java.util.Iterator; /** * 具体集合类 */ public class BookShelf implements Aggregate { Book[] books; int index = 0; public BookShelf(int maxium) { books = new Book[maxium]; } public Book getBookAt(int index) { return books[index]; } public void appendBook(Book newBook) { books[index++] = newBook; } public int getLength() { return index; } @Override public Iterator iterator() { return new BookShelfIterator(this); } }
package iterator; import java.util.Iterator; /** * 具体迭代类,Iterator是抽象迭代类 */ public class BookShelfIterator implements Iterator { private BookShelf bookShelf; private int index = 0; public BookShelfIterator(BookShelf bookShelf) { this.bookShelf = bookShelf; index = 0; } @Override public boolean hasNext() { if (index < bookShelf.getLength()) { return true; } else { return false; } } @Override public Object next() { Book book = bookShelf.getBookAt(index++); return book; } }
package iterator; import java.util.Iterator; /** * Created by marcopan on 17/4/7. */ public class IteratorTest { public static void main(String[] args) { BookShelf shelf = new BookShelf(4); shelf.appendBook(new Book("a")); shelf.appendBook(new Book("b")); shelf.appendBook(new Book("c")); shelf.appendBook(new Book("d")); Iterator it = shelf.iterator(); while (it.hasNext()) { Book book = (Book)it.next(); System.out.println(book.getName()); } } }
迭代器模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。