天天看点

【设计模式】——16,迭代器模式

(十六)迭代器模式

迭代器模式(Iterator Pattern)通过提供一种按顺序访问集合/容器的方法,而不暴露集合内部表示。它可以为不同的容器提供统一的遍历行为,而不用关心容器内元素的构造。

1,迭代器模式设计原则

1,抽象迭代器(Iterator):抽象迭代器定义访问和遍历元素接口;

2,具体迭代器(ConcreateIterator):提供具体遍历行为;

3,抽象容器(IAggregate):定义提供具体迭代器的接口;

4,具体容器(ConcreateAggregate):创建具体迭代器。

2,简单例子

手写一个迭代器,用于遍历课程信息。

public interface Iterator<E> {
    E next();
    boolean hasNext();
}
           
public class IteratorImpl<E> implements Iterator<E> {
//    实现迭代器内部维护一个list,element,index
    private List<E> list;
    private int cursor;
    private E element;

    public IteratorImpl(List<E> list) {
        this.list = list;
    }

//    获取下一个元素
    @Override
    public E next() {
        System.out.print("当前位置: "+cursor);
        element = list.get(cursor);
        cursor++;
        return element;
    }

//    判断下一个位置是否有元素
    @Override
    public boolean hasNext() {
        return cursor > list.size()-1 ? false : true;
    }
}
           
public interface CourseAggregate {
    void add(Course course);
    void remove(Course course);
    Iterator<Course> iterator();
}
           
public class CourseAggregateImpl implements CourseAggregate {

    private List courseList;

    public CourseAggregateImpl() {
        this.courseList = new ArrayList();
    }

    @Override
    public void add(Course course) {
        courseList.add(course);
    }

    @Override
    public void remove(Course course) {
        courseList.remove(course);
    }

    @Override
    public Iterator<Course> iterator() {
        return new IteratorImpl<>(courseList);
    }
}
           
public class Course {
    private String name;

    public Course(String name) {
        this.name = name;
    }
	//get,set
}
           
public class Client {
    public static void main(String[] args) {
        Course java = new Course("java");
        Course python = new Course("python");
        Course ai = new Course("ai");

        CourseAggregateImpl courseAggregate = new CourseAggregateImpl();

        courseAggregate.add(java);
        courseAggregate.add(python);
        courseAggregate.add(ai);

        print(courseAggregate);

    }

    public static void print(CourseAggregate courseAggregate) {
        Iterator<Course> iterator = courseAggregate.iterator();
        while (iterator.hasNext()) {
            Course course = iterator.next();
            System.out.println(course.getName());
        }
    }
}
           
【设计模式】——16,迭代器模式

3,迭代器模式的点评

迭代器模式将集合对象本身应该提供的元素迭代接口抽象到迭代器,使得集合对象无需关心具体迭代行为。它本质上是一种封装。一般对于自建的数据结构可以使用迭代器模式进行迭代,其他的使用框架自带的迭代器即可。

继续阅读