说明:这个模式已经被整合入Java的Collection.在大多数场合下无需自己制造一个Iterator,只要将对象装入Collection中,直接使用
Iterator进行对象遍历。(节选自“http://www.jdon.com/designpatterns/index.htm”)
非常常用的一个模式,使用上不用多说。Iterator接口倒是有些需要注意的地方,Iterator也是退耦的(指消除或减轻两个以上物体间在某方面相互影响的方法)。 1 迭代返回时的类型需要指定。因为next方法仅仅返回一个Object。最苯最方便的方法是手写代码指定类型。 2 但是容器中,由于容器持有的不一定是同一种类型,那么跌代的时候。该如何确定池有的类型呢?最安全的方法(可能很不方便)是需要用 户建立一个可以在返回时确定类型的跌代器。下面会有一个例子,是在构造函数中指定类型。
注意:以下的代码可能很像Proxy 模式,但是实际上它的建立思想却是Decorator 模式。
|
//TypedIterator.java import java.util.*;
public class TypedIterator implements Iterator { private Iterator imp; private Class type; public TypedIterator(Iterator it, Class type) { imp = it; this.type = type; }
public boolean hasNext() { return imp.hasNext(); }
public void remove() { imp.remove(); }
public Object next() { Object obj = imp.next(); if(!type.isInstance(obj)) throw new ClassCastException( "TypedIterator for type " + type + " encountered type: " + obj.getClass()); return obj; } } ///:~
|