元素:
1、Interator(迭代器)
提供访问和遍历元素的接口。一般包含hasNext和next方法。
2、ConcreteInterator(具体迭代器)
实现迭代器的接口,其中包含容器的实例,以遍历其中具体的元素,其中还需要有标记当前元素位置的变量。
3、Aggregate(聚合)
提供获取容器迭代器的接口函数。
4、ConcreteAggregate(具体聚合)
实现获取容器迭代器的接口,它其实就是被遍历的容器。
类图:
代码示例:
Aggregate.java
package Interface;
public interface Aggregate {
public abstract Iterator iterator();
}
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
Student.java
public class Student {
private String name = "";
public Student(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
}
ClassRoom.java
public class ClassRoom implements Aggregate{
private Student[] students;
private int last = 0;
private int maxsize;
public ClassRoom(int maxsize)
{
this.students = new Student[maxsize];
this.maxsize = maxsize;
}
public Student getStudentAt(int index)
{
return students[index];
}
public void addStudent(Student stu)
{
if(last<maxsize)
{
this.students[last] = stu;
last++;
}
else
System.out.println("max");
}
public int getSize()
{
return this.maxsize;
}
@Override
public Iterator iterator() {
// TODO Auto-generated method stub
return new ClassRoomIterator(this);
}
}
ClassRoomIterator.java
public class ClassRoomIterator implements Iterator{
private ClassRoom classroom;
private int index;
public ClassRoomIterator(ClassRoom cr)
{
this.classroom = cr;
this.index = 0;
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if(index<this.classroom.getSize())
return true;
else
return false;
}
@Override
public Object next() {
// TODO Auto-generated method stub
Student stu = this.classroom.getStudentAt(index);
index++;
return stu;
}
}
Main.java
public class Main {
public static void main(String[] args)
{
ClassRoom cr = new ClassRoom(4);
cr.addStudent(new Student("a"));
cr.addStudent(new Student("b"));
cr.addStudent(new Student("c"));
cr.addStudent(new Student("d"));
Iterator it = cr.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName());
}
}
}