目录
行为型模式:类或对象间如何交互、如何划分职责,从而更好的完成任务.
提供一个聚合对象,内部通过迭代器来访问聚合对象中的一系列数据,而不暴露聚合对象的内部实现.
例如,现在有一个班级的学生(包装在一个 List 容器中的聚合元素),我需要按照学号拿到每一个学生,此时就需要把遍历这个班级的学生(List 容器)交给迭代器完成.
迭代器模式主要包含以下角色:
实现上述学生案例.
- /**
- * 学生类
- */
- public class Student {
-
- private String name;
- private int id;
-
- public Student() {
- }
-
- public Student(String name, int id) {
- this.name = name;
- this.id = id;
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", id=" + id +
- '}';
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
- }
- /**
- * 抽象迭代器: 学生迭代器接口
- */
- public interface StudentIterator {
-
- boolean hasNext();
-
- Student next();
-
- }
- /**
- * 具体迭代器: 学生迭代器
- */
- public class StudentIteratorImpl implements StudentIterator{
-
- private List
list; - private int position;
-
- public StudentIteratorImpl(List
list) { - this.list = list;
- }
-
- @Override
- public boolean hasNext() {
- return position < list.size();
- }
-
- @Override
- public Student next() {
- Student current = list.get(position);
- position++;
- return current;
- }
-
- }
- /**
- * 抽象聚合: 学生聚合接口
- */
- public interface StudentAggregation {
-
-
- void addStudent(Student student);
-
- void removeStudent(Student student);
-
- StudentIterator getStudentIterator();
-
- }
- /**
- * 具体聚合: 学生聚合
- */
- public class StudentAggregationImpl implements StudentAggregation{
-
- private List
list = new ArrayList<>(); -
- @Override
- public void addStudent(Student student) {
- list.add(student);
- }
-
- @Override
- public void removeStudent(Student student) {
- list.remove(student);
- }
-
- @Override
- public StudentIterator getStudentIterator() {
- return new StudentIteratorImpl(list);
- }
-
- }
- public class Client {
-
- public static void main(String[] args) {
- StudentAggregationImpl aggregation = new StudentAggregationImpl();
- aggregation.addStudent(new Student("曹操", 1));
- aggregation.addStudent(new Student("诸葛亮", 2));
- aggregation.addStudent(new Student("赵云", 3));
- StudentIterator studentIterator = aggregation.getStudentIterator();
- while(studentIterator.hasNext()) {
- Student student = studentIterator.next();
- System.out.println(student);
- }
- }
-
- }
执行结果如下:
优点:
定义多种遍历方式:支持不同方式遍历一个聚合对象,可以在同一个聚合对象上顶一个多种遍历方式.
满足开闭原则:引入抽象层,增加新的聚合类和迭代器,都无需修改原有代码.
缺点:
增加了类的个数,一定程度上增加了系统复杂度.