阅读 150

Iterator pattern-迭代器模式

解决问题

提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示。

应用场景

作用主要用于对象的元素的遍历,相对于使用foreach,它可以屏蔽元素的集合的具体实现。

原理图

Aggregate:即聚合,比如Map, List, vector,当然也可以是一个直接对象,关键是你希望遍历的对象是什么。

Iterator:迭代器,提供元素遍历的方法。

示例

比如一个班级对象,我们经常要遍历一个班级内的学生成员。

public interface Iterator<T> {
    public boolean hasNext();
    public T next();
}
public class GradeIterator implements Iterator<ClassGrade.Student> {
    private ClassGrade grade;
    private int index = 0;

    public GradeIterator(ClassGrade grade) {
        this.grade = grade;
    }

    @Override
    public boolean hasNext() {
        if (grade == null || grade.getStudents() == null || grade.getStudents().isEmpty()) {
            return false;
        }
        if (grade.getStudents().size() <= index) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public ClassGrade.Student next() {
        if (this.hasNext()) {
            return grade.getStudents().get(index);
        }
        return null;
    }
}
public interface IClassGrade {
    public Iterator iterator();
}

@AllArgsConstructor
@Data
public class ClassGrade implements IClassGrade {
    private int grade;
    private String major;
    private List<Student> students;

    @Override
    public Iterator iterator() {
        return new GradeIterator(this);
    }

    @AllArgsConstructor
    @Data
    public static class Student {
        private int id;
        private String name;
        private int age;
    }

    public static void main(String[] args) {
        List<Student> students = Lists.newArrayList(new Student(1, "小红", 21),
                new Student(1, "小天", 20),new Student(1, "小明", 22));
        ClassGrade classGrade = new ClassGrade(1, "软件工程", students);
        Iterator iterator = classGrade.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
复制代码

参考

https://en.wikipedia.org/wiki/Design_Patterns