The Wayback Machine - https://web.archive.org/web/20240917125326/https://www.geeksforgeeks.org/design-patterns-in-java-iterator-pattern/
Open In App

Design Patterns in Java – Iterator Pattern

Last Updated : 08 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. Using design patterns you can make your code more flexible, reusable, and maintainable.

Types of design patterns: There are 3 types of Design Patterns in java that are depicted more clearly in a tabular format below.

  1. Behavioral Design Pattern
  2. Creational Design Pattern
  3. Structural Design Pattern
Behavioral Creational Structural
Iterator Pattern Factory Pattern Adapter Pattern
Interpreter Pattern Abstract Factory Pattern Bridge Pattern
Mediator Pattern Singleton Pattern Composite Pattern
Memento Pattern Prototype Pattern Decorator Pattern
Observer Pattern Builder Pattern Facade Pattern
State Pattern Object Pool Flyweight Pattern
Strategy Pattern   Proxy Pattern
Template Pattern    
Visitor Pattern    

Behavioural – Iterator Pattern

Here we will be discussing Iterator Pattern with an example.

  • The iterator pattern is a great pattern for providing navigation without exposing the structure of an object.
  • Traverse a container. In Java and most current programming languages, there’s the notion of a collection. List, Maps, Sets are all examples of a collection that we would want to traverse. Historically we use a loop of some sort and index into your collection to traverse it.
  • Doesn’t expose the underlying structure of the object we want to navigate. Navigating various structures may have different algorithms or approaches to cycle through the data.
  • Decouples the data from the algorithm used to traverse it

Design: Iterator Pattern

  • It is an interface-based design pattern. Whichever object you want to iterate over will provide a method to return an instance of an iterator from it.
  • Follows a factory-based method pattern in the way you get an instance of the iterator.
  • Each iterator is developed in such a way that it is independent of another.
  • Iterators also Fail Fast. Fail Fast means that iterators can’t modify the underlying object without an error being thrown.

  • The Collection interface is extended by the List Interface.
  • List Interface contains a factory method iterator(). This iterator factory method returns an instance of the Iterator Interface.
  • In the case of the list and its implementations, the underlying instances are ListIterator.
  • The ListIterator is an implementation of the Iterator interface that understands how to iterate over the various list objects in the Collection API. It declares the interface for objects in the composition.

There are some pitfalls of iterator which are as follows:

  • You don’t have access to an index of any sort. If you want to get an element of a certain position, there is no way to do that without just iterating though. In the case of sets and maps, there isn’t a method to grab an element at a certain index position
  • UniDirectional: It iterates objects in forwarding direction only.
  • Although iterator is the most efficient way to looping through objects of any sort. But in some cases, it may be slower than using an index and looping through it.

Example:

Java




// Java Program to Implement Behavioral>Iterator Pattern
 
// importing required package to
// implement Behavioral>Iterator Pattern
package com.demo.application;
 
// Importing required libraries
// Here Iterator Interface to
// use it to iterate over the elements
import java.util.Iterator;
 
 
// Class 1
 
// Car Class Implementing Iterable Interface so
// that we can implement the iterator method and
// add our own implementation
 
public class Car implements Iterable<String> {
  private String[] cars;
  private int index;
 
  // Default Constructor
  public Car() {
    cars = new String[10];
    index = 0;
  }
 
  // Method 1
  // Adding method to add Cars
  public void addCar(String car) {
    if (index == cars.length) {
      String[] largerCars = new String[cars.length + 5];
      System.arraycopy(cars, 0, largerCars, 0, cars.length);
      cars = largerCars;
      largerCars = null;
    }
    cars[index] = car;
    index++;
  }
 
  // Method 2
  // Implementing the iterator method and
  // adding your own implementation
  @Override
  public Iterator<String> iterator() {
    Iterator<String> it = new Iterator<String>() {
 
      private int currentIndex = 0;
 
      // Method 3
      // Finding whether during iteration if
      // there is next element or not
      @Override
      public boolean hasNext() {
        return currentIndex < cars.length && cars[currentIndex] != null;
      }
 
      // Method 4
      // Going to grab each car element by one by one
      // according to the index
      @Override
      public String next() {
        return cars[currentIndex++];
      }
 
      // Method 5
      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
 
    return it;
  }
 
  // Method 6
  // Main driver method
  public static void main(String[] args) {
 
    // Instantiating Car object
    Car cars = new Car();
 
    // Adding cars to the Array
    cars.addCar("Dodge");
    cars.addCar("Ferrari");
    cars.addCar("Sedan");
 
    // Creating an Iterator and pointing the cursor
    // to the index just before the first element in cars
    Iterator<String> carIterator = cars.iterator();
 
    // Checking whether the next element is available or not
    while (carIterator.hasNext()) {
      System.out.println(carIterator.next());
    }
  }
}


Conclusion:

  • An iterator is an efficient way to traverse an object.
  • Hides the algorithm from the client, so that simplicity for your client is contained within the algorithm that you have coated in the container you’re creating an iterator for
  • Helps us to simplify that client.
  • Helps us to take advantage of the for each syntax which definitely simplifies iterating over that object in a for each loop.

Further Read: Java Design Patterns Tutorial



Previous Article
Next Article

Similar Reads

Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
Iterator Method | JavaScript Design Pattern
Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is widely used in many programming languages, including
4 min read
Iterator Design Pattern
The Iterator pattern is a widely used design pattern in software development that provides a way to access the elements of an aggregate object (such as a list or collection) sequentially without exposing its underlying representation. Table of Content What is the Iterator Design Pattern?Components of Iterator Design Pattern Iterator Design Pattern
7 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Prototype Pattern | C++ Design Patterns
When designing software, it's crucial to make it efficient, easy to reuse, and simple to maintain. One way to achieve these goals is by using design patterns, and one such pattern is the Prototype Pattern. In this article, we'll explore the Prototype Design Pattern in the context of C++. Important Topics for the Prototype Pattern in C++ Design Patt
5 min read
Singleton Pattern | C++ Design Patterns
A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have only one instance of a class, for example, a singl
11 min read
Builder Pattern | C++ Design Patterns
The builder pattern is defined as a creational design pattern that separates the construction of a complex object from its representation, allowing us to create different representations of an object using the same construction process. It's beneficial when an object has many optional properties or configurations. The logic behind the Builder Patte
6 min read
Adapter Pattern | C++ Design Patterns
Adapter Pattern is a structural design pattern used to make two incompatible interfaces work together. It acts as a bridge between two incompatible interfaces, allowing them to collaborate without modifying their source code. This pattern is particularly useful when integrating legacy code or third-party libraries into your application. Important T
6 min read
Factory Method Pattern | C++ Design Patterns
Factory Method Pattern provides an interface for creating objects but leaves the actual object instantiation to derived classes. This allows for flexibility in object creation and promotes loose coupling between the creator (client code) and the concrete products. Important Topics for the Factory Method Pattern in C++ Design Patterns Real-World Exa
8 min read
Visitor Pattern | JavaScript Design Patterns
The visitor pattern is a behavioral design pattern that allows you to add new behaviors or operations to a set of objects without modifying their structure. It achieves this by separating the algorithm from the objects on which it operates. Important Topics for the Visitor Pattern in JavaScript Design Patterns Characteristics of the Visitor Pattern
12 min read
Command Pattern | C++ Design Patterns
The Command Pattern is a behavioral design pattern that focuses on encapsulating a request as an object, thereby decoupling the sender of the request from the receiver. This pattern allows you to parameterize objects with commands, delay or queue a request's execution, and support undoable operations. It's a fundamental pattern for implementing a w
7 min read
Observer Pattern | C++ Design Patterns
The Observer Pattern is a behavioral design pattern that defines a one-to-many dependency between objects, meaning that when one object (the subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern is used to build distributed event-handling systems and is a crucial part of many software archit
4 min read
Implementing Iterator pattern of a single Linked List
STL is one of the pillars of C++. It makes life a lot easier, especially when your focus is on problem-solving and you don’t want to spend time implementing something that is already available which guarantees a robust solution. One of the key aspects of Software Engineering is to avoid reinventing the wheel. Reusability is always preferred. While
10 min read