Java implements Iterator pattern
The Iterator pattern is a behavioral design pattern that allows clients to traverse the elements of a collection object one by one through Iterator without exposing the internal representation of the collection. This pattern encapsulates the iteration process in an independent Iterator object, so that the client can independently operate the collection object and Iterator object.
Applicable scenarios:
1. When you need to traverse the elements of an aggregate object without exposing its internal representation, you can use the Iterator pattern.
2. When you need to share the logic of element traversal on different aggregate objects, you can use the Iterator pattern.
3. When you need to provide different traversal methods, you can use the Iterator pattern.
The main benefits of this design pattern are:
1. Separation of collection objects and traversal logic makes the code easier to maintain and expand.
2. Provides a unified access interface for different aggregated objects, enhancing the flexibility and reusability of the code.
3. Simplify the use of the client, so that the client does not need to care about the internal structure of the collection object.
The following is the complete Java sample code:
//Iterator interface
interface Iterator<T> {
boolean hasNext();
T next();
}
//Aggregation interface
interface Aggregate {
Iterator<String> createIterator();
}
//Concrete Iterator implementation
class ConcreteIterator implements Iterator<String> {
private String[] names;
private int position;
public ConcreteIterator(String[] names) {
this.names = names;
this.position = 0;
}
public boolean hasNext() {
return position < names.length;
}
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
String name = names[position];
position++;
return name;
}
}
//Specific aggregation implementation
class ConcreteAggregate implements Aggregate {
private String[] names;
public ConcreteAggregate(String[] names) {
this.names = names;
}
public Iterator<String> createIterator() {
return new ConcreteIterator(names);
}
}
public class IteratorPatternDemo {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", "David"};
Aggregate aggregate = new ConcreteAggregate(names);
Iterator<String> iterator = aggregate.createIterator();
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
}
}
In the above code, we have defined a Iterator interface and an aggregate interface. The concrete Iterator and aggregate implement the corresponding interface.
In the main method of 'IteratorPatternDemo', we obtain a Iterator object by creating a concrete aggregate object. Then use the Iterator to traverse the elements in the aggregation object, and finally output the name of each element.