Design Pattern - Iterator

1 Introduction

1.1 Overview

The Iterator pattern is a behavioral design pattern that allows clients to access elements in an aggregate object one by one without exposing the internal representation of the aggregate object.

1.2 Design patterns

Design patterns are proven best practices for solving a specific problem, providing a general solution that can be reused in different scenarios.

1.3 Application scenarios of the iterator pattern

The iterator pattern is usually used when you need to traverse the elements in an aggregate object and do not want to expose its internal structure. For example, the collection framework in Java uses the iterator pattern to traverse the elements in a collection.
Insert image description here

1.4 The role of iterator pattern

The main function of the iterator pattern is to separate the traversal behavior of the aggregate object from its internal structure, so that the data structure of the aggregate object can be changed independently, and it can also provide multiple traversal methods.

2. Basic concepts

2.1 IteratorIterator

An iterator is an interface that defines methods for accessing and traversing the elements of an aggregate object. Iterators provide a unified access method that allows the client to directly access the elements in the aggregate object without relying on the specific type and internal structure.

2.2 Aggregation Aggregate

Aggregation is an interface that represents a collection object. Aggregation objects usually contain multiple elements and can provide multiple access methods, such as getting an element, adding and deleting elements, etc.

2.3 ConcreteAggregate

Concrete aggregation is a specific implementation of aggregation. It implements the aggregation interface and maintains the data structure of internal elements, such as arrays, linked lists, stacks, queues, etc.

3. Java implements the iterator pattern

3.1 Java collection framework

The Java collections framework is a set of classes and interfaces for storing and manipulating elements. The collection framework provides a variety of data structures and algorithms to meet the needs of different scenarios. All collection classes in the Java collection framework implement the Iterable interface, so you can use iterators for traversal operations.

3.2 Java iterator interface

Java provides an iterator interface Iterator, which defines methods for accessing and traversing elements in a collection. The iterator interface contains multiple methods, such as hasNext(), next(), remove(), etc.

The following is the definition of the iterator interface:

public interface Iterator<E> {
    
    
    boolean hasNext();
    E next();
    void remove();
}

3.3 Java iterator pattern implementation example

The following is a simple example of using the Iterator pattern to iterate over the elements in an aggregate object without exposing the internal structure by implementing the Iterable and Iterator interfaces.

import java.util.Iterator;

public class MyCollection<T> implements Iterable<T> {
    
    
    private T[] elements;
    private int size;

    public MyCollection(T[] elements) {
    
    
        this.elements = elements;
        this.size = elements.length;
    }

    @Override
    public Iterator<T> iterator() {
    
    
        return new MyIterator();
    }

    private class MyIterator implements Iterator<T> {
    
    
        private int index;

        public MyIterator() {
    
    
            this.index = 0;
        }

        @Override
        public boolean hasNext() {
    
    
            return index < size;
        }

        @Override
        public T next() {
    
    
            return elements[index++];
        }

        @Override
        public void remove() {
    
    
            throw new UnsupportedOperationException();
        }
    }
}
public class Client {
    
    
    public static void main(String[] args) {
    
    
        String[] names = {
    
    "Alice", "Bob", "Charlie", "Dave"};

        MyCollection<String> collection = new MyCollection<>(names);
        Iterator<String> iterator = collection.iterator();

        while (iterator.hasNext()) {
    
    
            String name = iterator.next();
            System.out.println(name);
        }
    }
}

In the above code, MyCollection implements the Iterable interface and returns an inner class MyIterator that implements the Iterator interface. MyIterator maintains an index variable, which represents the position of the currently traversed element. The hasNext() method is used to determine whether there is a next element. The next() method is used to return the current element and increase the index by one.
Insert image description here

4. Advantages and Disadvantages of the Iterator Pattern

4.1 Advantages

  • Separate the traversal behavior of the aggregate object from its internal structure, so that the data structure of the aggregate object can change independently without affecting the traversal process.
  • A variety of traversal methods are provided, and the client can choose the appropriate traversal method according to its own needs.
  • For different types of aggregate objects, a unified access method can be provided, making client coding simpler.

4.2 Disadvantages

  • For some aggregate objects, if their internal structure changes, the iterator may become invalid and a new iterator needs to be re-created.

5. The relationship between the iterator pattern and other design patterns

5.1 Iterator pattern and factory pattern

Iterator pattern and factory pattern can be used together with each other. In the factory pattern, you can use an iterator to traverse the elements in a product object to achieve comprehensive access to the product.

5.2 Iterator pattern and combination pattern

Iterator pattern and Combination pattern can be used together with each other. In the combination mode, you can use iterators to traverse all elements in the entire combination structure to achieve traversal and access to the combination structure.

5.3 Iterator pattern and template method pattern

Iterator pattern and template method pattern can also be used together with each other. In the template method pattern, you can use iterators as part of the template method to traverse and access elements in the aggregate object.

6. Summary

6.1 Application scenarios of the iterator pattern

The iterator pattern is usually used when you need to traverse the elements in an aggregate object and do not want to expose its internal structure. For example, the collection framework in Java uses the iterator pattern to traverse the elements in a collection.

6.2 The relationship between the iterator pattern and other design patterns

The iterator pattern can be used in conjunction with other design patterns such as factory pattern, combination pattern, and template method pattern to achieve more flexible programming.

6.3 Advantages and Disadvantages of the Iterator Pattern

The main advantage of the iterator pattern is to separate the traversal behavior of the aggregate object from its internal structure, so that the data structure of the aggregate object can be changed independently, and it can also provide multiple traversal methods. The disadvantage is that for some aggregate objects, if their internal structure changes, the iterator may become invalid and a new iterator needs to be re-created.

Guess you like

Origin blog.csdn.net/pengjun_ge/article/details/132603146