迭代器模式的定义:
迭代器模式又叫作游标模式,它提供一种按顺序访问集合/容器对象元素的一种方法,而又无须暴露集合内部表示。
迭代器模式可以为不同的容器提供一致的遍历行为,而不用关心容器内元素的组成结构,属于行为型设计模式。
迭代器模式的本质是把集合对象的迭代行为抽离到迭代器中,提供一致的访问接口。
迭代器模式的应用场景:
访问一个集合对象的内容而无须暴露它的内部表示。
为遍历不同的集合结构提供一个统一的访问接口。
迭代器模式的UML类图:
由上图可以看到,迭代器模式主要包含4个角色。
抽象迭代器(Iterator):抽象迭代器负责定义访问和遍历元素的接口。
具体迭代器(ConcreteIterator):提供具体的元素遍历行为。
抽象容器(IAggregate):负责定义提供具体迭代器的接口。
具体容器(ConcreteAggregate):创建具体迭代器。
手写自定义的集合迭代器:
总体来说,迭代器模式是非常简单的。这里以遍历课程为例,我们创建一个课程集合,集合中的每一个元素都是课程对象,
然后手写一个迭代器,将每一个课程对象的信息都读出来。
首先创建集合元素Course类。
public classCourse {privateString name;publicCourse(String name) {this.name =name;
}publicString getName() {returnname;
}
}
然后创建自定义迭代器Iterator接口。
public interface Iterator{
E next();booleanhasNext();
}
创建自定义的课程集合ICourseAggregate接口,该接口主要是定义集合的一些规范,并指定迭代器对象。
public interfaceICourseAggregate {voidadd(Course course);voidremove(Course course);
Iteratoriterator();
}
接着分别实现迭代器接口和集合接口。
public class IteratorImpl implements Iterator{private Listlist;private intcursor;privateE element;public IteratorImpl(Listlist) {this.list =list;
}publicE next() {
System.out.print("当前位置 " + cursor + " : ");
element=list.get(cursor);
cursor++;returnelement;
}public booleanhasNext() {if (cursor > list.size() - 1) {return false;
}return true;
}
}
public class CourseAggregateImpl implementsICourseAggregate {privateList courseList;publicCourseAggregateImpl() {this.courseList = newArrayList();
}public voidadd(Course course) {
courseList.add(course);
}public voidremove(Course course) {
courseList.remove(course);
}public Iteratoriterator() {return new IteratorImpl(courseList);
}
}
最后编写客户端测试代码。
public classTest {public static voidmain(String[] args) {
Course java= new Course("Java架构");
Course javaBase= new Course("Java基础");
Course design= new Course("设计模式");
Course ai= new Course("人工智能");
ICourseAggregate aggregate= newCourseAggregateImpl();
aggregate.add(java);
aggregate.add(javaBase);
aggregate.add(design);
aggregate.add(ai);
System.out.println("===========课程列表==========");
printCourse(aggregate);
aggregate.remove(ai);
System.out.println("===========删除操作之后的课程列表==========");
printCourse(aggregate);
}private static voidprintCourse(ICourseAggregate aggregate) {
Iterator i =aggregate.iterator();while(i.hasNext()) {
Course course=i.next();
System.out.println("《" + course.getName() + "》");
}
}
}
迭代器模式的优点:
多态迭代:为不同的聚合结构提供一致的遍历接口,即一个迭代接口可以访问不同的集合对象。
简化集合对象接口:迭代器模式将集合对象本身应该提供的元素迭代接口抽象到迭代器中,使集合对象无须关心具体迭代行为。
元素迭代功能多样化:每个集合对象都可以提供一个和多个不同的迭代器,使得同种元素得聚合结构可以有不同得迭代行为。
解耦迭代和集合:迭代器模式封装了具体得迭代算法,迭代算法的变化不会影响到集合对象的架构。
迭代器模式的缺点:
对于简单的遍历比如数组或者有序列表,使用迭代器遍历较为繁琐。
在日常开发中,我们几乎不需要自己写迭代器。除非要定制一个自己实现的数据结构对应的迭代器,否则,开源框架提供的API完全够用。