Appearance
迭代器模式
介绍
迭代器模式是一种行为设计模式,它提供了一种方法来顺序访问集合中的元素,而不暴露集合的内部表示。迭代器模式允许你在不暴露集合内部结构的情况下,遍历集合中的元素。
优点
- 提供了一种统一的方式来遍历集合中的元素,使得代码更加简洁和可读。
- 隐藏了集合的内部表示,使得代码更加灵活和可扩展。
- 可以实现多种遍历方式,例如正向遍历、反向遍历等。
缺点
- 增加了代码的复杂度,需要实现迭代器接口和集合类。
- 迭代器模式可能会导致代码的冗余,特别是在集合类中已经实现了遍历方法的情况下。
使用场景
- 当需要遍历集合中的元素,而不关心集合的内部表示时。
- 当需要实现多种遍历方式时,例如正向遍历、反向遍历等。
- 当需要隐藏集合的内部表示,使得代码更加灵活和可扩展时。
实现
java
public interface Iterator<T>{
boolean hasNext();
T next();
}
public interface IterableCollection<T> {
Iterator<T> createIterator();
}
public class ConcreteIterator<T> implements Iterator<T> {
private List<T> items;
private int position = 0;
public ConcreteIterator(List<T> items) {
this.items = items;
}
@Override
public boolean hasNext() {
return position < items.size();
}
@Override
public T next() {
if (hasNext()) {
T item = items.get(position);
position++;
return item;
}
throw new IndexOutOfBoundsException("No more elements");
}
}
public class ConcreteCollection<T> implements IterableCollection<T> {
private List<T> items = new ArrayList<>();
public void addItem(T item) {
items.add(item);
}
@Override
public Iterator<T> createIterator() {
return new ConcreteIterator<>(items);
}
}
public class Client {
public static void main(String[] args) {
ConcreteCollection<String> collection = new ConcreteCollection<>();
collection.addItem("Item 1");
collection.addItem("Item 2");
collection.addItem("Item 3");
Iterator<String> iterator = collection.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
运行结果:
txt
Item 1
Item 2
Item 3