模式介绍

迭代器模式是一种行为型设计模式,它提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。迭代器模式将遍历元素的责任从聚合对象中分离出来。

使用场景

  • 当需要访问一个聚合对象的内容而不暴露其内部表示时
  • 当需要支持对聚合对象的多种遍历方式时
  • 当需要为遍历不同的聚合结构提供一个统一的接口时

代码示例

// 迭代器接口
public interface Iterator {
    boolean hasNext();
    T next();
}

// 聚合接口
public interface Aggregate {
    Iterator createIterator();
}

// 具体迭代器
public class ConcreteIterator implements Iterator {
    private List items;
    private int position = 0;

    public ConcreteIterator(List items) {
        this.items = items;
    }

    @Override
    public boolean hasNext() {
        return position < items.size();
    }

    @Override
    public T next() {
        return items.get(position++);
    }
}

// 具体聚合类
public class ConcreteAggregate implements Aggregate {
    private List items = new ArrayList<>();

    public void addItem(T item) {
        items.add(item);
    }

    @Override
    public Iterator createIterator() {
        return new ConcreteIterator<>(items);
    }
}

优缺点

优点

  • 支持以不同的方式遍历一个聚合对象
  • 简化了聚合类的接口
  • 在同一个聚合上可以有多个遍历

缺点

  • 对于简单的遍历,使用迭代器模式可能会过于复杂
  • 抽象迭代器的设计难度较大
  • 需要额外维护迭代器对象