定义
提供一种方法,顺序访问一个容器对象中的各个元素,而不需要暴露该对象的内部表示。
迭代器模式又叫做游标模式,是行为型设计模式之一,理解起来也相对简单。
Java SDK 中涉及到多种该设计模式的使用,常用的 List、Map、数组等都可以通过迭代器模式便捷地访问内部对象。
实现
我们定义三个空接口,分辨对应水果、苹果、香蕉:
public interface IFruit {
}
public class Apple implements IFruit {
}
public class Banana implements IFruit {
}
再定义一个存放各种水果的容器:
public class FruitList {
private List<IFruit> fruitList;
public FruitList() {
this.fruitList = new ArrayList<>();
}
public void add(IFruit fruit) {
fruitList.add(fruit);
}
public Iterator<IFruit> iterator() {
return new FruitIterator(fruitList);
}
class FruitIterator implements Iterator<IFruit> {
private List<IFruit> fruitList;
private int currentIndex = 0;
public FruitIterator(List<IFruit> fruitList) {
this.fruitList = fruitList;
}
@Override
public boolean hasNext() {
return fruitList.size() > currentIndex && fruitList.get(currentIndex) != null;
}
@Override
public IFruit next() {
return fruitList.get(currentIndex ++);
}
@Override
public void remove() {
// no-op
}
}
}
Iterator 类为 JAVA SDK 中的迭代器接口。
定义客户类:
public class Client {
public static void main(String[] args) {
FruitList fruitList = new FruitList();
fruitList.add(new Apple());
fruitList.add(new Banana());
fruitList.add(new Banana());
fruitList.add(new Apple());
Iterator<IFruit> iterator = fruitList.iterator();
int i = 0;
while (iterator.hasNext()) {
System.out.println(iterator.next().getClass().getSimpleName());
}
}
}
由此可见,通过迭代器模式能够遍历容器对象内的元素,但是不必知晓其内部表示;同时,提高了扩展性,符合开闭原则。
当然,鱼与熊掌不可兼得,任何模式都不是完美的,迭代器模式也是。迭代器模式的缺点就是会产生大量的派生类,但是只要把握得当,将业务与实际开发相结合,寻求最佳解决方案才是设计模式的关键所在。
Android 中的迭代器模式
其实,迭代器模式最常见的使用场景,是在 JAVA SDK 中。当然,Android 中也提供了关于迭代器模式(游标模式)的实现。
Cursor 游标对象就是 Android 中提供的用于查询一系列数据库对象中元素的关键。
比如,SQLiteDatabase 类的 query 方法返回的对象就是一个包含多个对象的结果集游标对象 Cursor。
本文由
Fynn_ 原创,未经许可,不得转载!
网友评论