设计模式——迭代器模式
定义: 提供一个对象来顺序访问聚合对象中的一系列数据且不暴露聚合对象的内部
结构:
- 抽象聚合: 定义存储, 添加, 删除聚合元素以及创建迭代器对象的接口
- 具体聚合: 实现抽象聚合类, 返回一个具体迭代器的实例
- 抽象迭代器: 定义访问和遍历聚合元素的接口, 通常包含haseNext(), next()方法
- 具体迭代器: 实现抽象迭代器接口中所定义的方法, 完成对聚合对象的遍历, 记录遍历的当前位置
实现
抽象聚合
public interface Aggregate<T> {
void add(T obj);
void remove(T obj);
Iterator<T> getIterator();
}
具体聚合
@Data
@AllArgsConstructor
public class Student {
private String name;
private String number;
}
public class StudentAggregateImpl implements Aggregate<Student> {
private List<Student> list = new ArrayList<Student>();
public void add(Student obj) {
list.add(obj);
}
public void remove(Student obj) {
list.remove(obj);
}
public Iterator<Student> getIterator() {
return new StudentIteratorImpl(list);
}
}
抽象迭代
public interface Iterator<T> {
boolean hasNext();
T next();
}
具体迭代
public class StudentIteratorImpl implements Iterator<Student> {
private List<Student> list;
private int position = 0;
public StudentIteratorImpl(List<Student> list) {
this.list = list;
}
public boolean hasNext() {
return position < list.size();
}
public Student next() {
return list.get(position++);
}
}
Main
public class Main {
public static void main(String[] args) {
Aggregate<Student> aggregate = new StudentAggregateImpl();
aggregate.add(new Student("wtw", "123"));
aggregate.add(new Student("pk", "456"));
Iterator<Student> iterator = aggregate.getIterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
使用场景:
- 需要为聚合对象提供多种遍历方式时
- 需要为不同的聚合对象提供一个统一的接口时
- 访问聚合对象但不需要暴露其内部细节时