设计模式-迭代器模式
提供顺序访问聚合对象元素的方法,且不会暴露对象内部表示。
我们拿遍历教室中的学生来举例
先定义两个接口
public interface Iterator<T> {
T first();
T next();
boolean isDone();
T currentItem();
}
public interface Aggregate<T> {
Iterator<T> createIterator();
int count();
T get(int index);
void add(T t);
}
定义学生
@Data
@AllArgsConstructor
public class Student {
private String name;
}
教室的实现类
public class ClassRoom implements Aggregate<Student> {
private List<Student> list = new ArrayList<>();
@Override
public Iterator<Student> createIterator() {
return new StudentIterator(this);
}
@Override
public int count(){
return list.size();
}
@Override
public Student get(int index){
return list.get(index);
}
@Override
public void add(Student student) {
list.add(student);
}
}
迭代器的实现类
public class StudentIterator implements Iterator<Student> {
public StudentIterator(Aggregate<Student> aggregate) {
this.aggregate = aggregate;
}
private Aggregate<Student> aggregate;
private int index = 0;
@Override
public Student first() {
return aggregate.get(0);
}
@Override
public Student next() {
return aggregate.get(index++);
}
@Override
public boolean isDone() {
return index >= aggregate.count();
}
@Override
public Student currentItem() {
return aggregate.get(index);
}
}
测试
public class Demo {
public static void main(String[] args) {
ClassRoom room = new ClassRoom();
room.add(new Student("Tom"));
room.add(new Student("Bob"));
room.add(new Student("Peter"));
Iterator it = room.createIterator();
do {
System.out.println(it.next());
} while (!it.isDone());
}
}