文章目录
- 1、迭代器模式
- 2、案例
- 3、总结
- 4、在源码中的实际应用
1、迭代器模式
- 提供了一种遍历的方式
- 提供了一个对象来顺序访问聚合对象(集合、容器)中的一系列数据,而不会暴露聚合对象的内部表示
相关角色:
- 抽象聚合:定义存储、添加、删除元素、创建迭代器对象的方法
- 具体聚合:返回一个具体的迭代器实例
- 抽象迭代器:定义访问和遍历元素的方法,如hasNest()、next()
- 具体迭代器:实现元素的遍历,记录遍历的当前位置
2、案例
定义一个存储学生对象的容器对象,由迭代器实现遍历。
先定义Student这个业务类:
@Getter
@Setter
@AllArgsConstructs
public class Student{
private String name;
private String number;
}
定义抽象迭代器接口,声明hasNext、next两个抽象方法。next方法想要通用的话,就用泛型。
public interface StudentIterator {
boolean hasNext(); //判断是否还有元素
Student next(); //获取下一个元素
}
定义具体的迭代器类,重写所有的抽象方法。聚合元素类。
public class StudentIteratorImpl implements StudentIterator {
private List<Student> list;
private int position = 0; //用来记录遍历时的位置
public StudentIteratorImpl(List<Student> list) {
this.list = list;
}
@Override
public boolean hasNext() {
return position < list.size(); //有元素
}
@Override
public Student next() {
Student currentStudent = list.get(position);
position ++;
return currentStudent;
}
}
定义抽象容器类,提供:添加元素,删除元素,获取迭代器对象的方法
public interface StudentAggregate {
void addStudent(Student student);
void removeStudent(Student student);
StudentIterator getStudentIterator();
}
定义具体的容器类,重写所有的方法
public class StudentAggregateImpl implements StudentAggregate {
private List<Student> list = new ArrayList<Student>(); // 学生列表
@Override
public void addStudent(Student student) {
this.list.add(student);
}
@Override
public void removeStudent(Student student) {
this.list.remove(student);
}
@Override
public StudentIterator getStudentIterator() {
return new StudentIteratorImpl(this.list); //迭代器对象中的集合,和聚合对象中的集合,保持一致了
}
}
测试效果:
public class Client {
public static void main(String[] args) {
//创建聚合对象
StudentAggregate aggregate = new StudentAggregateImpl();
//添加元素
aggregate.addStudent(new Student("张三","001"));
aggregate.addStudent(new Student("李四","002"));
aggregate.addStudent(new Student("王五","003"));
aggregate.addStudent(new Student("赵六","004"));
//遍历对象
//获取迭代器对象
StudentIterator iterator = aggregate.getStudentIterator();
while(iterator.hasNest()){
System.out.println(iterator.next());
}
}
}
运行:
3、总结
优点:
-
支持以不同的方式遍历一个容器,如以上的一个具体迭代器是按顺序依次取,可定义个新的迭代器实现类去用(按需写next方法逻辑)
-
引入迭代器,聚合类(容器类)不用再自行提供数据遍历的方法
-
有抽象层的存在,再加个新的迭代器依旧符合开闭
适用场景:
- 需为容器类提供多种遍历方式(多个迭代器的实现类)
- 需为遍历不同结构的容器类提供一个统一的接口
- 当访问一个容器对象的元素,而不能暴露其内部结构细节
4、在源码中的实际应用
JDK中集合类的迭代器:
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator(); //list.iterator()方法返回的肯定是Iterator接口的子实现类对象
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
- List:抽象聚合类
- ArrayList:具体的聚合类
- Iterator:抽象迭代器
- list.iterator():返回的是实现了
Iterator
接口的具体迭代器对象
源码:
Itr是一个内部类,属于具体的迭代器类,实现了Iterator接口,并重写了next、hasNext方法。自己开发迭代器的话,也只需实现java.util.Iterator接口即可,类比上面的ArrayList。