定义:
提供了一种方法,顺序访问一个集合对象中的各个元素,而又不暴露该对象的内部表示
行为型
适用场景:
访问一个集合对象的内容而无需暴露它的内部表示
为遍历不同的集合结构提供一个统一的接口
优点:
分离了集合对象的遍历行为
缺点:
类的个数成对增加
相关设计模式:
迭代器模式和访问者模式
Coding
public class Course {
private String name;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public interface CourseAggregate {
void add(Course course);
void remove(Course course);
CourseIterator getCourseIterator();
}
import java.util.ArrayList;
import java.util.List;
public class CourseAggregateImpl implements CourseAggregate {
private List<Course> courses = new ArrayList<>();
@Override
public void add(Course course) {
courses.add(course);
}
@Override
public void remove(Course course) {
courses.remove(course);
}
@Override
public CourseIterator getCourseIterator() {
return new CourseIteratorImpl(courses);
}
}
public interface CourseIterator {
boolean hasCourse();
Course nextCourse();
}
import java.util.List;
public class CourseIteratorImpl implements CourseIterator {
private List<Course> courseList;
private int position;
private Course course;
public CourseIteratorImpl(List<Course> courseList) {
this.courseList = courseList;
}
@Override
public boolean hasCourse() {
return position < courseList.size();
}
@Override
public Course nextCourse() {
return courseList.get(position++);
}
}
public class Test {
public static void main(String[] args) {
CourseAggregate courseAggregate = new CourseAggregateImpl();
courseAggregate.add(new Course("1-Course"));
courseAggregate.add(new Course("2-Course"));
courseAggregate.add(new Course("3-Course"));
courseAggregate.add(new Course("4-Course"));
courseAggregate.add(new Course("5-Course"));
CourseIterator courseIterator = courseAggregate.getCourseIterator();
while (courseIterator.hasCourse()) {
System.out.println(courseIterator.nextCourse().getName());
}
}
}