需求:给大家举个例子,现在假设,有一个教室类,里面包含了一堆学生,我现在要遍历教室里的学生,怎么来玩儿?
- 面向 Iterator 接口编程,无论底层的数据结构和迭代算法如何变化,调用者都不用修改代码;
- 其实一般很少自己写这个 iterator 模式的,一般都是在集合编程中使用,尤其 JDK 已经封装好的iterator模式,如果要对某个类中的集合进行遍历,由那个集合类返回一个 iterator 回来,我们统一面向 iterator 迭代器接口来编程遍历,提高系统整体的可维护性,可扩展性;
package com.example.designpattern.iterator;
import java.util.Arrays;
/**
* 用迭代器模式的实现
*/
public class IteratorPatternDemo {
public static void main(String[] args) {
Student student1 = new Student("小明");
Student student2 = new Student("小王");
Classroom classroom = new Classroom(2);
classroom.addStudent(student1);
classroom.addStudent(student2);
Iterator iterator = classroom.iterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.println(student);
}
}
/**
* 学生类
*/
public static class Student{
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
/**
* 定义一个迭代器借口, 包含两个方法: 是否有下一个元素;返回下一个元素
*/
public interface Iterator{
public boolean hasNext();
public Object next();
}
/**
* 代表了一个集合类
*/
public interface Aggregate{
public Iterator iterator();
}
/**
* 教师类
*/
public static class Classroom implements Aggregate{
private Student[] students;
private int last = 0;
public Classroom(int size){
this.students = new Student[size];
}
public Student getStudent(int index){
return students[index];
}
public void addStudent(Student student){
this.students[last] = student;
last++;
}
public int getLength(){
return last;
}
/**
* 返回一个教室迭代器,其中封装了教室自己,让迭代器可以获取教室中的数据
* @return
*/
public Iterator iterator() {
return new ClassroomIterator(this);
}
}
/**
* 教师迭代器
*/
public static class ClassroomIterator implements Iterator{
private Classroom classroom;
private int index;
public ClassroomIterator(Classroom classroom) {
this.classroom = classroom;
this.index = 0;
}
public boolean hasNext() {
if(index<classroom.getLength()){
return true;
}else{
return false;
}
}
public Object next() {
Student student = classroom.getStudent(index);
index++;
return student;
}
}
}