迭代器模式
迭代器模式 迭代器模式又叫做游标(Cursor)模式,其作用是 提供一种方法访问一个容器元素中的各个对象,而又不暴露该对象的内部细节 。 迭代器模式结构 迭代器模式由以下角色组成: 1、迭代器角色 负责定义访问和遍历元素的接口 2、具体迭代器角色 实现迭代器接口,并要记录遍历中的当前位置 3、容器角色 负责提供创建具体迭代器角色的接口 4、具体容器角色 实现创建具体迭代器角色的接口,这个具体迭代器角色与该容器的结构相关 迭代器模式在JDK中的应用及解读 迭代器模式就不自己写例子了,直接使用JDK中的例子。为什么我们要使用迭代器模式,思考一个问题,假如我有一个ArrayList和一个LinkedList: List<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(1); arrayList.add(2); List<Integer> linkedList = new LinkedList<Integer>(); linkedList.add(3); linkedList.add(4); 如何去遍历这两个List相信每个人都很清楚: System.out.println("ArrayList:"); for (int i = 0; i < arrayList.size(); i++) System.out