- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 308字
- 2021-06-25 20:52:38
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());
推薦閱讀
- 軟件安全技術
- C及C++程序設計(第4版)
- Linux核心技術從小白到大牛
- C# Programming Cookbook
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- INSTANT Sencha Touch
- JavaScript+Vue+React全程實例
- Microsoft System Center Orchestrator 2012 R2 Essentials
- Scala編程實戰(原書第2版)
- Nginx實戰:基于Lua語言的配置、開發與架構詳解
- Access 2010數據庫應用技術(第2版)
- 時空數據建模及其應用
- uni-app跨平臺開發與應用從入門到實踐
- Struts 2.x權威指南
- UX Design for Mobile