官术网_书友最值得收藏!

Implementation

The iterator pattern is based on two abstract classes or interfaces, which can be implemented by pairs of concrete classes. The class diagram is as follows:

The following classes are used in the iterator pattern:

  • Aggregate: The abstract class that should be implemented by all the classes and can be traversed by an iterator. This corresponds to the java.util.Collection interface.
  • Iterator: This is the iterator abstraction that defines the operations to traverse the aggregate object along with the one to return the object.
  • ConcreteAggregate: Concrete aggregates can implement internally different structures, but expose the concrete iterator, which deals with traversing the aggregates.
  • ConcreteIterator: This is the concrete iterator that deals with a specific concrete aggregate class. In practice, for each ConcreteAggregate, we have to implement a ConcreteIterator.

Using the iterators in Java is probably one of the things every programmer does in daily life. Let's see how we can implement an iterator. First of all, we should define a simple iterator interface:

public interface Iterator
{
public Object next();
public boolean hasNext();
}
We create the aggregate:
public interface Aggregate
{
public Iterator createIterator();
}

Then we implement a simple Aggregator, which maintains an array of String values:

public class StringArray implements Aggregate 
{ 
  private String values[]; 
  public StringArray(String[] values) 
{ this.values = values; } public Iterator createIterator() { return (Iterator) new StringArrayIterator(); } private class StringArrayIterator implements Iterator { private int position; public boolean hasNext() { return (position < values.length); } public String next() { if (this.hasNext()) return values[position++]; else return null; } } }

We nested the iterator class in the aggregate. This is the best option because the iterator needs access to the internal variables of the aggregator. We can see here how it looks:

String arr[]= {"a", "b", "c", "d"};
StringArray strarr = new StringArray(arr);
for (Iterator it = strarr.createIterator(); it.hasNext();)
System.out.println(it.next());
主站蜘蛛池模板: 太康县| 罗源县| 隆子县| 嵊泗县| 浦城县| 遂昌县| 台湾省| 万盛区| 台州市| 镇坪县| 南陵县| 伊春市| 盐源县| 泰顺县| 台东县| 邛崃市| 西乌珠穆沁旗| 浮梁县| 保定市| 邓州市| 石屏县| 灌南县| 尼玛县| 东宁县| 永丰县| 沁源县| 进贤县| 桐乡市| 广丰县| 广昌县| 扶风县| 南投县| 大兴区| 孝义市| 孟连| 玛纳斯县| 邮箱| 鄂托克旗| 阜平县| 礼泉县| 桑日县|