模式概述
迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。迭代器模式属于行为型模式。
在软件开发中,用来存储多个成员对象的这些类称为聚合类(Aggregate Classes),对应的对象称为聚合对象。为了更加方便地操作这些聚合对象,同时可以很灵活地为聚合对象增加不同的遍历方法,可以使用一个称为迭代器的角色来访问一个聚合对象中的元素但又不需要暴露它的内部结构。
迭代器模式提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor)。通过引入迭代器,客户端无须了解聚合对象的内部结构即可实现对聚合对象中成员的遍历,还可以根据需要很方便地增加新的遍历方式。
模式结构
迭代器模式由四个部分组成:抽象聚合角色、具体聚合角色、抽象迭代器角色、具体迭代器角色等。
1、抽象聚合(Aggregate)角色:定义存储、添加、删除聚合对象以及创建迭代器对象的接口。
2、具体聚合(ConcreteAggregate)角色:实现抽象聚合类,返回一个具体迭代器的实例。
3、抽象迭代器(Iterator)角色:定义访问和遍历聚合元素的接口,通常包含 hasNext()、first()、next() 等方法。
4、具体迭代器(Concretelterator)角色:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。
迭代器分为主动迭代和被动迭代,主要是相对于客户端而言的。如果客户端控制迭代的进程,那么这样的迭代就是主动迭代,相反就是被动迭代。使用主动迭代的客户端会明显调用迭代器的next()等迭代方法,在遍历的过程中向前迭代,而客户端在使用被动迭代时,明显不会调用迭代方法,而是由迭代器自行推进遍历过程。而我们在开发过程中大部分都是使用的主动迭代。
实现代码
假设有一个复杂形状对象ComplexShape由多个简单对象Shape组成,Shape对象可以是三角形、圆形、正方形等。通过使用迭代器ShapeIterator,就可以依次访问各个简单形状Shape。
抽象聚合角色
public interface ComplexShapeInterface {
public abstract void add(Shape shape);
public abstract void remove(Shape shape);
public abstract Iterator getIterator();
}
具体聚合角色
public class ComplexShape implements ComplexShapeInterface{
ArrayList<Shape> shapes = new ArrayList<Shape>();
@Override
public void add(Shape shape) {
this.shapes.add(shape);
}
@Override
public void remove(Shape shape) {
this.shapes.remove(shape);
}
@Override
public Iterator getIterator() {
return new ShapeIterator(shapes);
}
}
抽象迭代器角色
public interface Iterator {
public boolean hasNext();
public Object next();
}
具体迭代器角色
public class ShapeIterator implements Iterator{
ArrayList<Shape> shapes;
int index;
public ShapeIterator(ArrayList<Shape> shapes){
this.index = -1;
this.shapes = shapes;
}
@Override
public boolean hasNext() {
if(index < shapes.size() - 1){
return true;
}
return false;
}
@Override
public Object next() {
index ++;
return shapes.get(index);
}
}
测试类、其他类
public class Shape {
public String name;
public Shape(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
public class Demo {
public static void main(String[] args) {
ComplexShape complexShape = new ComplexShape();
complexShape.add(new Shape("square"));
complexShape.add(new Shape("triangle"));
Iterator iterator = complexShape.getIterator();
while(iterator.hasNext()){
Shape shape = (Shape) iterator.next();
System.out.println(shape.getName());
}
}
}
输出结果为:
square
triangle