Iterator模式 --一个一个遍历

在Java中的for语句中 i++的作用是让 i 的值在每次循环后自增1,这样就可以访问数组中的下一个元素、下下一个元素、再下下一个元素,也就实现了从头至尾逐一遍历数组元素的功能。

将这里的循环变量 i的作用抽象化、通用化后形成的模式,在设计模式中称为 Iterator 模式

示例程序

  • Aggregate接口

    Aggregate接口是索要遍历的集合的接口。实现了该接口的类将称为一个可以保持多个元素的集合。

public interface Aggregate {

     public abstract Iterator iterator();
}

Aggregate接口中的iterator 方法将会生成一个用于遍历集合的迭代器。想要遍历集合中的元素的时候可以调用该方法来生成一个实现了Iterator接口的类的实例。

  • Iterator接口
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}

  hasNext()方法主要用于循环终止条件。

  next()方法用于返回集合中的一个元素,并且为了在下次调用next方法时正确地反回下一个元素,在该方法中还需将迭代器移动至下一个元素的处理。

  • Book类
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
  • BookShelf类
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;
} public Itrator iterator() {
return new BookShelfIterator(this);
}
}

BookShelf类是用来表示书架的类,将该类作为Book的集合进行处理,实现了Aggregate接口。

  • BookShelfIterator类
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;
}
}

BookShelfIterator类是一个迭代器的实现,它持有一个将要遍历的集合BookShelf书架。

  • Main类
public class Main{
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(4);
bookShelf.appendBook(new Book("倚天屠龙记"));
bookShelf.appendBook(new Book("葵花宝典"));
bookShelf.appendBook(new Book("九阳真经"));
bookShelf.appendBook(new Book("神雕侠侣"));
Iterator it = bookShelf.iterator();
while (it.hasNext()){
Book book = (Book) it.next();
System.out.println(book.getName());
}
}
}

总结

  • 为何要使用Iterator

引入Iterator后可以将遍历与实现分离开来,在遍历时只需调用迭代器的方法,而不用关心具体集合实现类的方法。假设以后需要对集合类的实现方式进行修改,只要集合中的Iterator方法能正确的返回Iterator实例,即使不对迭代器的使用者进行修改,遍历代码都能正常工作。

设计模式的作用就是帮助我们编写可复用的类。“可复用”就是将类实现为“组件”,当一个组件发生改变时,不需要对其他的组件进行修改或只需很小的修改即可应对。

  • 多个Iterator

将遍历功能置于Aggregate角色之外,是Iterator模式的一个特征。根据这几个特征,可以针对一个具体的ConcreateAggregate角色编写多个ConcreteIterator角色。

  • 对JAVA集合进行遍历删除时务必要用迭代器。
 private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

ArrayList中的迭代器实现

最新文章

  1. Oracle启动报错ORA-03113解决
  2. mysql添加用户和用户权限
  3. (一)熟悉执行流程——基于ThinkPHP3.2的内容管理框架OneThink学习
  4. HIVE删除表数据
  5. 模板:LCS(最长公共子序列)
  6. linux下软件安装与卸载
  7. 【转】10分钟了解设计模式(C#)
  8. $(srctree) is not clean, please run &#39;make mrproper&#39;
  9. vue学习笔记 实例(二)
  10. OC中自定义构造方法
  11. SSM框架下 Failed to load resource: the server responded with a status of 404 (Not Found)错误
  12. python基础—sys与os库
  13. 监控服务器配置(一)-----Prometheus安装配置
  14. mycat跟踪分析
  15. Java相关问题整理
  16. 如何向微软 Docs 和本地化社区提交翻译贡献
  17. LwIP Application Developers Manual3---链路层和网络层协议之IPV6,ICMP,IGMP
  18. Kafka一些常见资源汇总
  19. 【vue】饿了么项目-页面骨架开发
  20. dubbo 响应超时异常: com.alibaba.dubbo.remoting.TimeoutException: Waiting server-side response timeout.

热门文章

  1. 如何判断float值有效
  2. java 调用启动远程shell脚本,启动spark
  3. 【Medium翻译】Java抽象类有什么用?
  4. Unity调用Android相册
  5. 【XSY2558】圆上的蚂蚁 Ants on circle
  6. Anaconda的安装和详细介绍(带图文)
  7. LNMP+Redis架构部署
  8. php imagick生成图片需要注意的问题
  9. maven安装与在eclipse中配置
  10. 如何给HTML标签中的文本设置修饰线