迭代器模式
迭代器模式是顺序访问对象的各个元素,而又不用暴露对象的内部表示。
我们创建一个宠物仓库类,然后对其内部的各个宠物进行遍历。
Iterator接口
public interface Iterator {
public boolean hasNext();
public Object next();
}
Container接口
public interface Container {
public Iterator getIterator();
}
宠物仓库类
public class PetRepository implements Container{
public String[] pets = {"cat", "dog"};
@Override
public Iterator getIterator() {
return new PetIterator();
}
private class PetIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
if (index < pets.length) {
return true;
}
return false;
}
@Override
public Object next() {
if (hasNext()) {
return pets[index++];
}
return null;
}
}
}
测试迭代器模式
public class TestIterator {
public static void main(String[] args) {
PetRepository petRepository = new PetRepository();
for(Iterator iter = petRepository.getIterator(); iter.hasNext();) {
String pet= (String) iter.next();
System.out.println("pet: " + pet);
}
}
}