Design Pattern9
Design Pattern9
PRACTICAL 9
Aim: Write program to understand Iterator pattern
Theory:
The Iterator design pattern is a behavioral pattern used in object-oriented programming to provide a
way to access elements of a collection sequentially without exposing its underlying representation.
In Java, this pattern is widely utilized to traverse through collections such as lists, sets, and maps in
a standardized and efficient manner.
• Support for Multiple Traversal Methods: It allows for different types of iterators to be
implemented for the same collection, enabling various traversal strategies (e.g., forward,
backward, or filtered iteration) without modifying the collection's code.
• Adherence to the Single Responsibility Principle: By isolating the iteration logic into a
separate class, the Iterator pattern adheres to the Single Responsibility Principle, ensuring
that the collection class is solely responsible for managing its elements, while the iterator
handles the traversal.
• Common Use Cases: The Iterator pattern is commonly used in scenarios where collections
need to be traversed in a consistent manner, such as in database query results, file system
navigation, or custom data structures. It is also integral to Java's java.util.Iterator interface,
which is widely used in the Java Collections Framework.
In summary, the Iterator pattern is a powerful tool for managing the traversal of collections, offering
a clean, flexible, and reusable approach to accessing elements without exposing the internal
structure of the collection.
Implementation:
import java.util.*;
class Employee {
private String name;
private double salary;
this.salary = salary;
}
// Iterator interface
interface Iterator<T> {
boolean hasNext();
T next();
}
// Aggregate interface
interface Aggregate<T> {
Iterator<T> createIterator();
}
// Concrete Iterator
class EmployeeIterator implements Iterator<Employee> {
private int currentIndex = 0;
private List<Employee> employees;
@Override
public boolean hasNext() {
return currentIndex < employees.size();
}
@Override
public Employee next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return employees.get(currentIndex++);
}
}
// Concrete Aggregate
class Company implements Aggregate<Employee> {
private List<Employee> employees;
@Override
public Iterator<Employee> createIterator() {
return new EmployeeIterator(employees);
}
}
// Main class
public class Main {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Alice", 50000));
employees.add(new Employee("Bob", 60000));
employees.add(new Employee("Charlie", 70000));
double totalSalary = 0;
while (iterator.hasNext()) {
totalSalary += iterator.next().getSalary();
}
Output: