【设计模式】Iterator迭代器设计模式(容器和容器的遍历)

本文涉及的产品
容器服务 Serverless 版 ACK Serverless,952元额度 多规格
容器服务 Serverless 版 ACK Serverless,317元额度 多规格
容器镜像服务 ACR,镜像仓库100个 不限时长
简介:
在遍历容器元素的时候,有很多初学者在疑惑,为什么返回一个iterator我就能够去遍历这个容器了呢?

今天我们就来深入剖析一下迭代器iterator的设计模式(循序渐进的剖析,一定要耐心看完)

iterator是"四人帮"所定义的23种设计模式之一(不太难,也不是非常重要,只是在遍历容器的时候能够用到)

首先需要读这个总结的同志掌握面向对象的思想。

1.我们先自己写一个可以动态添加对象的容器
建立一个新的Java工程:Iterator
创建一个包:cn.edu.hpu.iterator
在包下创建类ArrayList:
我们要在容器内首先添加一个add方法,用于向容器内添加元素
再写一个size方法,用于查找容器元素个数

ArrayList.java:
package cn.edu.hpu.iterator;

public class ArrayList {
	//我们要用数组模拟一个可以添加任意大小元素的容器
	//首先我们固定一个数组空间,再添加元素的时候,我们去判断
	//这个空间是不是满了,如果满了再在此基础上再添加一个固定空间
	//往下依次类推,这样就有了可以添加任意大小元素的容器
	//当然,容器大小一定不可能超过计算机内存的大小
	Object[] objects=new Object[10]; 
	int index=0;//代表objects的下一个空的位置在哪里
	
	//添加元素方法
	public void add(Object o){
		if(index==objects.length){
			//原来的数组已满,要做扩展(原长度X2)
			Object[] newObjects=new Object[objects.length*2];
			//把objects内容拷贝到新的数组newObjects上
			System.arraycopy(objects, 0, newObjects, 0, objects.length);//数组拷贝函数
			objects=newObjects;//之后把newObjects拷贝给objects数组
		}
		objects[index]=o;
		index++;
	}
	
	//获取容器元素个数方法
	public int size(){
		return index;
	}
}


测试:

package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.ArrayList;

public class ArrayListTest {
	public static void main(String[] args) {
		ArrayList al=new ArrayList();
		for(int i=0;i<20;i++){
			al.add(new Object());
		}
		System.out.println(al.size());
	}
}
测试结果:20

我们就完成了这样一个容器,这个容器是用数组来实现的。容器比数组好在哪里呢?使用容器就不需要考虑到数组的边界问题了,容器可以动态拓展。想往里面装就add就行了,想知道大小直接size就可以了。

2.我们加一个辅助类Cat
Cat.java:
package cn.edu.hpu.iterator;

public class Cat {
	private int id;


	public Cat(int id) {
		super();
		this.id = id;
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
}

以后添加元素就添加这个就可以了,因为可以通过id值知道添加了哪些数据
如测试:
package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.ArrayList;

public class ArrayListTest {
	public static void main(String[] args) {
		ArrayList al=new ArrayList();
		for(int i=0;i<20;i++){
			al.add(new Cat(i));
		}
		System.out.println(al.size());
	}
}


3.OK,现在我腻歪了,不想用ArrayList容器了,我想用其它容器去装Cat,这个新的容器我们底层不用数组实现了,我们用链表来实现。(需要你先了解数据结构中的链表概念)
建立一个新容器类LinkedList,一个节点类Node
LinkedList.java:
package cn.edu.hpu.iterator;

public class LinkedList {
	Node head=null;//头节点(以后的元素通过next得到)
	Node tail=null;//尾节点
	int size=0;
	public void add(Object o){
		Node n=new Node(o,null);
		if(head==null){
			head=n;
			tail=n;
		}
		tail.setNext(n);
		tail=n;
		size++;
		
	}
	
	public int size(){
		return size;
	}
}


Node.java:
package cn.edu.hpu.iterator;

public class Node {
	private Object data;
	private Node next;
	
	
	public Node(Object data, Node next) {
		super();
		this.data = data;
		this.next = next;
	}
	
	public Object getData() {
		return data;
	}
	
	public void setData(Object data) {
		this.data = data;
	}
	
	public Node getNext() {
		return next;
	}
	
	public void setNext(Node next) {
		this.next = next;
	}
	
}

测试:
package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.LinkedList;

public class LinkedListTest {
	public static void main(String[] args) {
		LinkedList ll=new LinkedList();
		for(int i=0;i<20;i++){
			ll.add(new Cat(i));
		}
		System.out.println(ll.size());
	}
}
测试结果:20


我们实现了两个内部原理完全不同的容器,那么下面我们来看:

4.考虑容器的可替换性
什么叫做可替换性?考虑我们使用容器的客户端类,想使这些容器可以任意的替换,其它代码不用改变,这就需要我们把所有容器的对外提供的方法统一起来。
解决方案:
我们写一个统一的接口Collection,定义一些统一的规范,让所有容器去实现这个接口。
Collection.java:
package cn.edu.hpu.iterator;

public interface Collection {
	void add(Object o);
	int size();
}

ArrayList.java:
package cn.edu.hpu.iterator;

public class ArrayList implements Collection{
	
	Object[] objects=new Object[10]; 
	int index=0;
	public void add(Object o){
		if(index==objects.length){
			
			Object[] newObjects=new Object[objects.length*2];
			
			System.arraycopy(objects, 0, newObjects, 0, objects.length);
			objects=newObjects;
		}
		objects[index]=o;
		index++;
	}
	
	public int size(){
		return index;
	}
}

LinkedList.java:
package cn.edu.hpu.iterator;

public class LinkedList implements Collection{
	Node head=null;
	Node tail=null;
	int size=0;
	public void add(Object o){
		Node n=new Node(o,null);
		if(head==null){
			head=n;
			tail=n;
		}
		tail.setNext(n);
		tail=n;
		size++;
		
	}
	
	public int size(){
		return size;
	}
}

这样我们就用Collection接口来实现对不同容器对外方法的统一。
在我们测试的时候就可以使用这种方式来实现容器:
Collection c=new ArrayList();
我对ArrayList不满意,就可以改成
Collection c=new LinkedList();

小结:针对接口编程就不需要考虑具体的实现类是什么,所以你的程序会更加灵活,要替换其它实现的时候,只需换一个位置(当然如果你写在配置文件上,你连代码都不用改)。

5.接下来重点来了,我们的容器需要一个非常非常重要的功能-------遍历
我想遍历容器中的所有元素,如何去做?
当然可以这样来写:
package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.ArrayList;
import cn.edu.hpu.iterator.Collection;

public class ArrayListTest {
	public static void main(String[] args) {
		Collection c=new ArrayList();
		for(int i=0;i<20;i++){
			c.add(new Cat(i));
		}
		System.out.println(c.size());
		
		ArrayList al=(ArrayList)c;
		for(int i=0;i<al.index;i++){
			Cat cat=(Cat)al.objects[i];
			System.out.print(cat.getId()+" ");
		}
	}
}
结果:
20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

但是,当我们将Collection的实现改为LinkedList的时候下面的遍历方法就不行了。
这个时候就需要一种统一的遍历方式。

每一种容器都应该有它自己的一种遍历方式,我们要想方设法的给他们统一起来,但是每种容器的遍历器的实现又不一样,所以统一遍历方式只能用一种共同的实现方式,接口或抽象类的方式。

所以我们这么写:
定义一个接口Iterator:
package cn.edu.hpu.iterator;

public interface Iterator {
	Object next();
	boolean hasNext();
}

其中有两个未实现的方法:next和hasNext。
我要求任何一个容器都必须给我一个实现了这个接口的类的对象,
具体的实现交给具体的容器自己去实现。实现完了之后,我肯定知道,
这个对象就实现这两个方法了,有了这两个方法,我就可以实现对这
个容器的遍历了。

我们在Collection中加入返回Iterator的未实现方法
package cn.edu.hpu.iterator;

public interface Collection {
	void add(Object o);
	int size();
	Iterator iterator();
}

ArrayList实现了iterator()这个方法
public Iterator iterator(){
		return null;
	}

测试:
package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.ArrayList;
import cn.edu.hpu.iterator.Collection;
import cn.edu.hpu.iterator.Iterator;

public class ArrayListTest {
	public static void main(String[] args) {
		Collection c=new ArrayList();
		for(int i=0;i<20;i++){
			c.add(new Cat(i));
		}
		System.out.println(c.size());
		
		/*之前的方法
                ArrayList al=(ArrayList)c;
		for(int i=0;i<al.index;i++){
			Cat cat=(Cat)al.objects[i];
			System.out.print(cat.getId()+" ");
		}*/

                //使用统一遍历器的遍历方法
                ArrayList al=(ArrayList)c;
		Iterator it=c.iterator();
		while(it.hasNext()){
			Object o=it.next();
			Cat cat=(Cat)o;
			System.out.print(cat.getId()+" ");
		}
	}
}
这样我们怎么改变Collection的实现类,都不影响遍历方式。

6.当然我没还没有写Iterator的实现,我们来写实现:
我们在ArrayList中写一个内部类ArrayListIterator,实现Iterator接口:
package cn.edu.hpu.iterator;

public class ArrayList implements Collection{

	Object[] objects=new Object[10]; 
	int index=0;
	
	public void add(Object o){
		if(index==objects.length){
			
			Object[] newObjects=new Object[objects.length*2];
	
			System.arraycopy(objects, 0, newObjects, 0, objects.length);
			objects=newObjects;
		}
		objects[index]=o;
		index++;
	}
	
	public int size(){
		return index;
	}
	
	public Iterator iterator(){
		return new ArrayListIterator();
	}
	
	private class ArrayListIterator implements Iterator{


		private int currentIndex=0;
		
		@Override
		public boolean hasNext() {
			if(currentIndex>index) return false;
			else return true;
		}

		@Override
		public Object next() {
			Object o=objects[currentIndex];
			currentIndex++;
			return o;
		}
		
	}
}

测试:
package cn.edu.hpu.iterator;

import cn.edu.hpu.iterator.ArrayList;
import cn.edu.hpu.iterator.Collection;
import cn.edu.hpu.iterator.Iterator;


public class ArrayListTest {
	public static void main(String[] args) {
		Collection c=new ArrayList();
		for(int i=0;i<20;i++){
			c.add(new Cat(i));
		}
		System.out.println(c.size());


                //使用统一遍历器的遍历方法
		ArrayList al=(ArrayList)c;
		Iterator it=c.iterator();
		while(it.hasNext()){
			Object o=it.next();
			Cat cat=(Cat)o;
			System.out.print(cat.getId()+" ");
		}
	}
}
测试结果:
20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

在我们的JavaAPI中的ArrayList也实现了Java的Collection接口,同样提供了一个方法,
叫iterator(),这个方法返回了一个实现了Iterator接口的对象。

现在大家明白iterator()方法到底是干什么用的,它返回的接口又是什么意思了吧?

作业:
这个LinkedList也需要写一个iterator方法,返回一个实现了Iterator的对象。该如何写?

这是我自己写的: http://blog.csdn.net/acmman/article/details/43924261

感谢马士兵老师的"设计模式"视频提供的帮助
转载请注明出处:http://blog.csdn.net/acmman/article/details/43920153
相关文章
|
2月前
|
设计模式 存储 Android开发
c++的学习之路:18、容器适配器与反向迭代器
c++的学习之路:18、容器适配器与反向迭代器
28 0
|
2月前
|
存储 算法 C语言
【C++ 迭代器实现 终篇】深入理解C++自定义容器和迭代器的实现与应用
【C++ 迭代器实现 终篇】深入理解C++自定义容器和迭代器的实现与应用
83 0
|
2月前
|
C++ 容器
【C++之迭代器】遍历容器
【C++之迭代器】遍历容器
|
2月前
|
存储 算法 Java
容器【双例集合、TreeMap容器的使用、 Iterator接口、Collections工具类】(四)-全面详解(学习总结---从入门到深化)(中)
容器【双例集合、TreeMap容器的使用、 Iterator接口、Collections工具类】(四)-全面详解(学习总结---从入门到深化)
54 0
|
5天前
|
算法 C++ 容器
C++之vector容器操作(构造、赋值、扩容、插入、删除、交换、预留空间、遍历)
C++之vector容器操作(构造、赋值、扩容、插入、删除、交换、预留空间、遍历)
11 0
|
6天前
|
算法 编译器 Linux
【C++/STL】:vector容器的底层剖析&&迭代器失效&&隐藏的浅拷贝
【C++/STL】:vector容器的底层剖析&&迭代器失效&&隐藏的浅拷贝
9 0
|
2月前
|
设计模式 XML 数据格式
【设计模式】探秘迭代器模式:如何像数星星一样遍历你的数据集?
【设计模式】探秘迭代器模式:如何像数星星一样遍历你的数据集?
26 0
|
2月前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
2月前
|
算法 程序员 C语言
【C++ 迭代器】深入探讨 C++ 迭代器:标准与自定义容器中的 begin() 和 cbegin()
【C++ 迭代器】深入探讨 C++ 迭代器:标准与自定义容器中的 begin() 和 cbegin()
70 0
|
2月前
|
存储 算法 安全
容器【双例集合、TreeMap容器的使用、 Iterator接口、Collections工具类】(四)-全面详解(学习总结---从入门到深化)
容器【双例集合、TreeMap容器的使用、 Iterator接口、Collections工具类】(四)-全面详解(学习总结---从入门到深化)
32 0