提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。
定义一个可以存储学生对象的容器对象,将遍历该容器的功能交由迭代器实现。
类图:
/**
* 抽象迭代器接口
*/
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 removerStudent(Student student);
// 获取迭代器对象
StudentIterator getStudentIterator();
}
public class StudentAggregateImpl implements StudentAggregate{
private List<Student> list = new ArrayList<>();
public StudentAggregateImpl() {
}
public StudentAggregateImpl(List<Student> list) {
this.list = list;
}
@Override
public void addStudent(Student student) {
list.add(student);
}
@Override
public void removerStudent(Student student) {
list.remove(student);
}
@Override
public StudentIterator getStudentIterator() {
return new StudentIteratorImpl(list);
}
}
public class Student {
private String name;
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
}
public Student(String name, String number) {
this.name = name;
this.number = number;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", number='" + number + '\'' +
'}';
}
}
public class Test01 {
public static void main(String[] args) {
// 创建聚合对象
StudentAggregateImpl aggregate = new StudentAggregateImpl();
// 添加
aggregate.addStudent(new Student("张三", "001"));
aggregate.addStudent(new Student("李四", "002"));
aggregate.addStudent(new Student("王五", "003"));
aggregate.addStudent(new Student("小明", "004"));
// 遍历
// 获取迭代器
StudentIterator studentIterator = aggregate.getStudentIterator();
// 遍历
while (studentIterator.hasNext()){
// 获取元素
Student student = studentIterator.next();
System.out.println(student.toString());
}
}
}