深入理解迭代器模式:从理论到实践

46 阅读1分钟

深入理解迭代器模式:从理论到实践

什么是迭代器模式?

迭代器模式是一种行为设计模式,它提供了一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其底层表示。

代码示例

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

public class ConcreteIterator<T> implements Iterator<T> {
    private List<T> list;
    private int index = 0;

    public ConcreteIterator(List<T> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        return index < list.size();
    }

    @Override
    public T next() {
        return list.get(index++);
    }
}

应用场景

设计一个图书馆管理系统,通过迭代器模式遍历书架上的书籍。

(文章内容超过2000字,此处为简化示例)