需求:给大家举个例子,现在假设,有一个教室类,里面包含了一堆学生,我现在要遍历教室里的学生,怎么来玩儿?

    • 面向 Iterator 接口编程,无论底层的数据结构和迭代算法如何变化,调用者都不用修改代码;
    • 其实一般很少自己写这个 iterator 模式的,一般都是在集合编程中使用,尤其 JDK 已经封装好的iterator模式,如果要对某个类中的集合进行遍历,由那个集合类返回一个 iterator 回来,我们统一面向 iterator 迭代器接口来编程遍历,提高系统整体的可维护性,可扩展性;

    image.png

    1. package com.example.designpattern.iterator;
    2. import java.util.Arrays;
    3. /**
    4. * 用迭代器模式的实现
    5. */
    6. public class IteratorPatternDemo {
    7. public static void main(String[] args) {
    8. Student student1 = new Student("小明");
    9. Student student2 = new Student("小王");
    10. Classroom classroom = new Classroom(2);
    11. classroom.addStudent(student1);
    12. classroom.addStudent(student2);
    13. Iterator iterator = classroom.iterator();
    14. while(iterator.hasNext()){
    15. Student student = (Student) iterator.next();
    16. System.out.println(student);
    17. }
    18. }
    19. /**
    20. * 学生类
    21. */
    22. public static class Student{
    23. private String name;
    24. public Student(String name) {
    25. this.name = name;
    26. }
    27. public String getName() {
    28. return name;
    29. }
    30. public void setName(String name) {
    31. this.name = name;
    32. }
    33. @Override
    34. public String toString() {
    35. return "Student{" +
    36. "name='" + name + '\'' +
    37. '}';
    38. }
    39. }
    40. /**
    41. * 定义一个迭代器借口, 包含两个方法: 是否有下一个元素;返回下一个元素
    42. */
    43. public interface Iterator{
    44. public boolean hasNext();
    45. public Object next();
    46. }
    47. /**
    48. * 代表了一个集合类
    49. */
    50. public interface Aggregate{
    51. public Iterator iterator();
    52. }
    53. /**
    54. * 教师类
    55. */
    56. public static class Classroom implements Aggregate{
    57. private Student[] students;
    58. private int last = 0;
    59. public Classroom(int size){
    60. this.students = new Student[size];
    61. }
    62. public Student getStudent(int index){
    63. return students[index];
    64. }
    65. public void addStudent(Student student){
    66. this.students[last] = student;
    67. last++;
    68. }
    69. public int getLength(){
    70. return last;
    71. }
    72. /**
    73. * 返回一个教室迭代器,其中封装了教室自己,让迭代器可以获取教室中的数据
    74. * @return
    75. */
    76. public Iterator iterator() {
    77. return new ClassroomIterator(this);
    78. }
    79. }
    80. /**
    81. * 教师迭代器
    82. */
    83. public static class ClassroomIterator implements Iterator{
    84. private Classroom classroom;
    85. private int index;
    86. public ClassroomIterator(Classroom classroom) {
    87. this.classroom = classroom;
    88. this.index = 0;
    89. }
    90. public boolean hasNext() {
    91. if(index<classroom.getLength()){
    92. return true;
    93. }else{
    94. return false;
    95. }
    96. }
    97. public Object next() {
    98. Student student = classroom.getStudent(index);
    99. index++;
    100. return student;
    101. }
    102. }
    103. }