提供一种方法来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。
package com.strife.pattern.iterator;
/**
* 迭代器模式
*
* @author mengzhenghao
* @date 2022/6/2
*/
public class IteratorCode {
public static void main(String[] args) {
String[] strs = new String[]{"str1", "str2", "str3", "str4"};
ConcreteAggregate<String> aggregate = new ConcreteAggregate<>(strs);
Iterator<String> iterator = new ConcreteIterator<>(aggregate);
while (iterator.hasNext()) {
final String ne = iterator.next();
System.out.println(ne);
}
}
}
/** 抽象迭代器 */
interface Iterator<T> {
boolean hasNext();
T next();
}
/** 具体迭代器 */
class ConcreteIterator<T> implements Iterator<T> {
/** 持有被迭代的聚合对象 */
private ConcreteAggregate<T> aggregate;
/** 当前迭代的索引位置 */
private int index;
/** 聚合对象的大小 */
private int size;
public ConcreteIterator(ConcreteAggregate<T> aggregate) {
this.aggregate = aggregate;
this.index = -1;
this.size = aggregate.size();
}
@Override
public boolean hasNext() {
return index < aggregate.size() - 1;
}
@Override
public T next() {
return aggregate.getElement(++index);
}
}
/** 统一的聚合接口,将客户端和具体聚合解耦 */
abstract class AbstractAggregate<T> {
/** 创建相应迭代器对象的接口 */
public abstract Iterator<T> createIterator();
}
/** 具体聚合,持有对应的集合 */
class ConcreteAggregate<T> extends AbstractAggregate<T> {
private T[] array;
public ConcreteAggregate(T[] array) {
this.array = array;
}
@Override
public Iterator createIterator() {
return new ConcreteIterator(this);
}
public T getElement(int index) {
if (index < array.length) {
return array[index];
} else {
return null;
}
}
public int size() {
return array.length;
}
}