The Iterator Pattern is a behavioral design pattern that provides a way to access the elements of a collection sequentially without exposing its underlying representation.
The Iterator Pattern decouples the iteration logic from the collection itself. It provides a standard interface for traversing a collection without knowing its internal structure.
Key features:
- Encapsulation: Hides the complexity of traversal logic.
- Consistency: Provides a standard way to access elements.
- Flexibility: Supports different types of collections.
- Abstraction: Decouples iteration logic from the collection's internal structure.
- Flexibility: Supports multiple ways to traverse a collection.
- Readability: Simplifies code by abstracting traversal logic.
The implementation of the Iterator Pattern can be found in:
Iterator.java
: Interface defining the traversal methods.Collection.java
: Represents a collection of elements.ConcreteIterator.java
: Concrete implementation of the iterator.ConcreteCollection.java
: Concrete implementation of the collection.Main.java
: Demonstrates the usage of the Iterator Pattern.
To see the Iterator Pattern in action, refer to the Main.java
file. It demonstrates traversing a collection using an iterator.
- Java Collections Framework:
- Iterators are used to traverse collections like
ArrayList
orHashSet
.
- Iterators are used to traverse collections like
- Game Development:
- Traversing game objects or scenes in a game engine.
classDiagram
class Aggregate {
+CreateIterator()
}
class ConcreteAggregate {
+CreateIterator()
}
class Iterator {
+First()
+Next()
+hasNext()
}
class ConcreteIterator {
+First()
+Next()
+hasNext()
}
Client --> Iterator
Client --> Aggregate
Aggregate <|-- ConcreteAggregate
Iterator <|-- ConcreteIterator
ConcreteAggregate --> ConcreteIterator : constructs
ConcreteIterator --> ConcreteAggregate : has (traverses)
Note
If the UML above is not rendering correctly, you can view the diagram from the iterator_uml.png
file.
- The Iterator Pattern separates traversal logic from the collection's structure.
- It simplifies traversal and supports multiple traversal algorithms.
- Use it when you need to access elements of a collection without exposing its internals.