行为模式--迭代器模式

一、基本介绍

迭代器模式也叫游标模式,是用来遍历集合对象的,这里的集合也叫容器,包含了一组对象,容器比如有:数组、链表、树等。
迭代器模式的作用是将集合对象的遍历操作从集合类中拆分出来,放到迭代器类中,让两者职责更加单一。

一个完整的迭代器模式应该涉及到容器迭代器。容器包含容器接口、容器实现类;迭代器又包含迭代器接口、迭代器实现类。

迭代器模式

二、代码示例

  • 迭代器接口
// 接口定义方式一
public interface Iterator<E> {
  boolean hasNext(); 
  void next();
  E currentItem();
}

// 接口定义方式二
public interface Iterator<E> {
  boolean hasNext();
  E next(); //其实是合并了 后移一位和返回当前元素两个操作
}
  • Array的迭代器实现
    将对集合的操作解耦出来
public class ArrayIterator<E> implements Iterator<E> {
  private int cursor;
  private ArrayList<E> arrayList; //组合了Array集合

  public ArrayIterator(ArrayList<E> arrayList) {
    this.cursor = 0;
    this.arrayList = arrayList;
  }

  @Override
  public boolean hasNext() {
    return cursor != arrayList.size(); //注意这里,cursor在指向最后一个元素的时候,hasNext()仍旧返回true。
  }

  @Override
  public void next() {
    cursor++;
  }

  @Override
  public E currentItem() {
    if (cursor >= arrayList.size()) {
      throw new NoSuchElementException();
    }
    return arrayList.get(cursor);
  }
}
  • ArrayIterato的使用
public class Demo {
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("xzg");
    names.add("wang");
    names.add("zheng");
    
    Iterator<String> iterator = new ArrayIterator(names);
    while (iterator.hasNext()) {
      System.out.println(iterator.currentItem());
      iterator.next();
    }
  }
}

三、优势

对复杂的数据结构进行遍历时使用迭代器模式可以拆分复杂的遍历方式,如图的深度优先遍历、广度优先遍历和树的前中后序遍历、层次遍历。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 迭代器模式 迭代器模式是一种行为设计模式, 让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合...
    紫藤lvy阅读 159评论 0 0
  • 标签(空格分隔):迭代器模式 迭代器模式:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表...
    查无此人_chazz阅读 198评论 0 0
  • 一、迭代器模式的定义用于遍历集合对象。“集合对象”也可以叫“容器”“聚合对象”,实际上就是包含一组对象的对象,比如...
    熊本极客阅读 345评论 0 1
  • 本文学习新的行为性设计模式,迭代器模式:它用来遍历集合对象。不过,很多编程语言都将迭代器作为一个基础的类库,直接提...
    舍是境界阅读 169评论 0 1
  • 行为型设计模式主要解决的就是“类或对象之间的交互”问题。 观察者模式 在对象之间定义一个一对多的依赖,当一个对象状...
    DreamSunny阅读 408评论 0 0