定义
迭代器模式:提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。
案例
/**
* 迭代器接口
*/
public interface Iterator {
boolean hasNext();
Object next();
}
/**
* 外部类接口
*/
public interface Container {
Iterator getIterator();
}
/**
* 名字仓库类
*/
public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
//内部迭代器类
private class NameIterator implements Iterator {
private int index; //编译器默认初始化为0
@Override
public boolean hasNext() {
if (index < names.length) {
return true;
}
return false;
}
@Override
public Object next() {
if (hasNext()) {
return names[index++];
}
return null;
}
}
}
public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}
迭代器模式通常需要声明一个内部迭代器类,如例子中的NameIterator类,由于该类为成员类,故可以访问外部类的数据集并遍历。