迭代器模式
2022-02-09 本文已影响0人
c_gentle
iterator模式
需求:给大家举个例子,现在假设,有一个教室类,里面包含了一堆学生,我现在要遍历教室里的学生,怎么来玩儿
public interface Aggregate {
public abstract Iterator iterator();
}
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
public class Student {
private String name;
public Student (String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Classroom implements Aggregate {
private Student[] students;
private int last = 0;
public Classroom(int size) {
this.students = new Student[size];
}
public Student getStudents(int size) {
return students[size];
}
public void addStudent(Student student) {
this.students[last] = student;
last++;
}
public int getLength() {
return last;
}
@Override
public Iterator iterator() {
return new ClassroomIterator(this);
}
}
public class ClassroomIterator implements Iterator {
private Classroom classroom;
private int index;
public ClassroomIterator(Classroom classroom) {
this.classroom = classroom;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < classroom.getLength()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
Student student=classroom.getStudents(index);
index++;
return student;
}
}
public class Main {
public static void main(String[] args) {
Classroom classroom = new Classroom(2);
classroom.addStudent(new Student("小李"));
classroom.addStudent(new Student("王三"));
Iterator iterator = classroom.iterator();
while (iterator.hasNext()){
System.out.println(((Student)iterator.next()).getName());
}
}
}
面向Iterator接口编程,无论底层的数据结构和迭代算法如何变化,调用者都不用修改代码
高内聚,低耦合,漂亮
其实一般很少自己写这个iterator模式的,一般都是在集合编程中使用,尤其是如果要对集合元素遍历过程中做插入删除操作,那就用iterator,体验JDK已经封装好的iterator模式,加深印象,如果要对某个类中的集合进行遍历,由那个集合类返回一个iterator回来,我们统一面向iterator迭代器接口来编程遍历,提高系统整体的可维护性,可扩展性
如果自己写iterator模式,一般是研发底层的框架,比如提供某个数据给外部遍历,那么可以使用iterator模式自己封装迭代器,以后阶段如果有机会,我们也会去实践