迭代器模式用于顺序访问集合对象的元素,而无需知道集合的底层表示,屏蔽了细节用一种更便携的方式访问集合对象。html
定义一个获取迭代对象的接口ide
public interface Container { public Iterator getIterator(); }
定义迭代对象方法spa
public interface Iterator { public boolean hasNext(); public Object next(); }
建立一个集合类时,须要在该集合类中添加一个内部类实现Iterator接口,用于判断是否有元素及获取元素。code
集合类须要实现Container接口,提供一个获取实现了Iterator的内部类对象的方法,用于后续遍历。htm
//模拟集合类 public class NameRepository implements Container{ private String[] names = {"hcf","zrx","gcmh"}; //获取实现了Iterator接口的内部类 @Override public Iterator getIterator() { // TODO Auto-generated method stub return new NameRepositoryIterator(); } //集合内部实现Iterator接口的内部类。 private class NameRepositoryIterator implements Iterator{ private int index = (names != null && names.length > 0) ? 0 : -1; @Override public boolean hasNext() { // TODO Auto-generated method stub if(index < names.length) { return true; }else { return false; } } @Override public Object next() { // TODO Auto-generated method stub return names[index++]; } } }
Main对象
public class Main { public static void main(String[] args) { NameRepository nameRepository = new NameRepository(); Iterator ite = nameRepository.getIterator(); while(ite.hasNext()) { System.out.println(ite.next()); } } }
运行结果:
hcf
zrx
gcmh
参考资料:blog
https://www.runoob.com/design-pattern/iterator-pattern.html接口