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中的迭代器实现

【设计模式大法】Iterator模式的更多相关文章

  1. 设计模式之Iterator模式

    STL里的iterator就是应用了iterator模式. 一.什么是迭代模式 Iterator模式也叫迭代模式,是行为模式之一,它把对容器中包含的内部对象的访问委让给外部类,使用Iterator按顺 ...

  2. Java设计模式之Iterator模式

    分类: [java]2013-07-15 10:58 917人阅读 评论(0) 收藏 举报 所谓Iterator模式,即是Iterator为不同的容器提供一个统一的访问方式.本文以java中的容器为例 ...

  3. 设计模式—迭代器Iterator模式

    什么是迭代器模式? 让用户通过特定的接口访问容器的数据,不需要了解容器内部的数据结构. 首先我们先模仿集合中ArrayList和LinkedList的实现.一个是基于数组的实现.一个是基于链表的实现, ...

  4. 设计模式——迭代器(Iterator)模式

    概述 迭代器模式简单的说(按我目前的理解)就是一个类提供一个对外迭代的接口,方面调用者迭代.这个迭代接口至少包括两个方法:hasNext()--用于判断是否还有下一个,next()--用于取出下一个对 ...

  5. 设计模式之Iterator模式(2)

    这篇文章比较简单,作一个笔记. 模拟Iterator. Iterator接口: package cn.asto.Interator; public interface Iterator { publi ...

  6. 设计模式:Iterator模式

    目的:将数据的存储和数据的查询分开,降低数据的耦合性 继承关系图: 例子: //定义迭代器接口 template<typename T> class Iterator { public: ...

  7. 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)

    原文:乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) 作者:weba ...

  8. Java设计模式(12)迭代模式(Iterator模式)

    上了这么多年学,我发现一个问题,好象老师都很喜欢点名,甚至点名都成了某些老师的嗜好,一日不点名,就饭吃不香,觉睡不好似的,我就觉得很奇怪,你的课要是讲的好,同学又怎么会不来听课呢,殊不知:“误人子弟, ...

  9. 设计模式学习--迭代器模式(Iterator Pattern)和组合模式(Composite Pattern)

    设计模式学习--迭代器模式(Iterator Pattern) 概述 ——————————————————————————————————————————————————— 迭代器模式提供一种方法顺序 ...

随机推荐

  1. SpringCloud之Feign负载均衡(四)

    整合Feign pom.xml <dependency> <groupId>org.springframework.cloud</groupId> <arti ...

  2. 详细讲解IPython

    ipython是一个python的交互式shell,比默认的python shell好用得多,支持变量自动补全,自动缩进,支持bash shell命令,内置了许多很有用的功能和函数.学习ipython ...

  3. ElasticSearch head插件安装与配置

    下载 下载地址:https://github.com/mobz/elasticsearch-head 安装 1. 下载到本地 git clone 2. 安装 grunt npm install -g ...

  4. 证明:S = 1 + 1/2 + 1/4 + 1/8 + 1/16 + ·······,求证 S = 2

    证: S = 1 + 1/2 + 1/4 + 1/8 + 1/16 + ······· (式1) 将式1左右两边除以2,得: S/2 = 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + ...

  5. Python进阶函数

    一.函数的动态参数 之前我们说过了传参, 如果我们需要给一个函数传参, 而参数又是不确定的. 或者我给一个函数传很多参数, 我的形参就要写很多, 很麻烦, 怎么办呢. 我们可以考虑使用动态参数. 动态 ...

  6. numpy.array 合并和分割

    # 导包 import numpy as np numpy.array 的合并 .concatenate() 一维数组 x = np.array([1, 2, 3]) # array([1, 2, 3 ...

  7. CHRONY 时间服务器

    时间同步服务chrony ntp network time Protocol之前使用的同步协议 chrony ntp协议的实现,兼容网络中的ntp服务(centos7之后就不再使用ntp,转而使用ch ...

  8. MQ应用之解耦

    简介 消息队列 MQ 既可为分布式应用系统提供异步解耦和削峰填谷的能力,同时也具备互联网应用所需的海量消息堆积.高吞吐.可靠重试等特性. 应用场景 削峰填谷:诸如秒杀.抢红包.企业开门红等大型活动时皆 ...

  9. docker简介及安装

    Docker : 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...

  10. Unity 简记(1)--TileMap

    ## Tilemap是unity中自带的快速构建2D场景的工具,优点是省时省力, 1 使用方法 在场景创建一个Tilemap 打开TilePalette ​ 3.创建一个新的Palette,将地图切割 ...