6.8 迭代器模式
6.8.1 概述
定义:提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。
6.8.2 结构
迭代器模式主要包含以下角色:
- 抽象聚合(Aggregate)角色:定义存储、添加、删除聚合元素以及创建迭代器对象的接口。
- 具体聚合(ConcreteAggregate)角色:实现抽象聚合类,返回一个具体迭代器的实例。
- 抽象迭代器(Iterator)角色:定义访问和遍历聚合元素的接口,通常包含 hasNext()、next() 等方法。
- 具体迭代器(Concretelterator)角色:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。
6.8.3 案例实现
【例】定义一个可以存储学生对象的容器对象,将遍历该容器的功能交由迭代器实现,涉及到的类如下:
代码如下:
定义迭代器接口,声明hasNext、next方法
class Student {private String name;private String number;public Student(String name, String number) {this.name = name;this.number = number;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getNumber() {return number;}public void setNumber(String number) {this.number = number;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", number='" + number + '\'' +'}';}
}
//抽象迭代器角色接口
interface StudentIterator {boolean hasNext();Student next();
}
//具体迭代器角色类
class StudentIteratorImpl implements StudentIterator {private List<Student> list;private int position = 0;public StudentIteratorImpl(List<Student> list) {this.list = list;}@Overridepublic boolean hasNext() {return position < list.size();}@Overridepublic Student next() {Student currentStudent = list.get(position);position++;return currentStudent;}
}
interface StudentAggregate {void addStudent(Student student);void removeStudent(Student student);StudentIterator getStudentIterator();
}
class StudentAggregateImpl implements StudentAggregate {private List<Student> list = new ArrayList<Student>(); // 学生列表@Overridepublic void addStudent(Student student) {this.list.add(student);}@Overridepublic void removeStudent(Student student) {this.list.remove(student);}@Overridepublic StudentIterator getStudentIterator() {return new StudentIteratorImpl(list);}
}
class Client{public static void main(String[] args) {//创建聚合对象StudentAggregateImpl studentAggregate = new StudentAggregateImpl();//添加元素studentAggregate.addStudent(new Student("张三","1001001"));studentAggregate.addStudent(new Student("李四","1001002"));studentAggregate.addStudent(new Student("王二","1001003"));studentAggregate.addStudent(new Student("麻子","1001004"));//遍历聚合对象StudentIterator studentIterator = studentAggregate.getStudentIterator();while(studentIterator.hasNext()){Student student = studentIterator.next();System.out.println(student.toString());}}
}
Student{name='张三', number='1001001'}
Student{name='李四', numbe