This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Welcome to today’s lesson. Today we’re going to look at a pattern that is often used in coding but never implemented itself —- iterator pattern. This month, I will talk about Java design patterns in detail. Please click on the profile picture and follow my column. I will keep updating.

Series of articles:

Singletons of design patterns

The factory model of design pattern

The builder pattern of design patterns

Proxy patterns of design patterns

The visitor pattern of design patterns

Adaptor patterns for design patterns

The designer mode of the design mode

Java state pattern | monitoring state change anytime and anywhere

Java observer pattern | how to notice things change

Java mode | how to record history information memorandum

. Under continuous update

Without further ado, let’s get to the point

Iterator pattern

The Iterator pattern, which I’m sure you’re familiar with java.util.Iterator, is called an Iterator in Java. To be clear, a Java Iterator is not a collection; it is a method for accessing a collection that can be used to iterate over collections such as ArrayLists and HashSets.

So, look at the official definition below

The iterator mode, also known as the Cursor mode, was originally defined as: iterators provide a way to access the elements of a container object without exposing the inner details of the object.

Today I’m going to start with a brief introduction to Java iterators, and then simply implement the Iterator pattern myself. Because in normal development, we are more likely to use it directly and rarely implement an iterator from zero.

But today we’re going to focus on the iterator pattern, and the goal is to understand how it works.

java Iterator

The Iterator interface is also a member of the Java Collections framework. Unlike the collections and Map families, which are primarily used as containers, An Iterator, as its name suggests, is primarily used to iterate over elements in a Collection. An Iterator object is also called an Iterator

This interface defines four methods:

  • Boolean hasNext() : Used to determine if there is a next element. Returns True if the set being iterated over has not been iterated through

  • E next() : returns the next element in the set, if there is still one

  • Remove () : remove elements from the collection that were last returned by the next() method

  • This method has been enhanced since java8. You can use Lambda expressions to iterate over collection elements

As you can see, Java iterators are designed to provide a common operation interface for various containers. In this way, the traversal of the container is decoupled from its underlying implementation. The iterator pattern is this idea. Let’s implement a simple iterator ourselves.

Implement your own iterators

Here’s a picture (from the web) :

From the picture above, we can see four key roles:

  • Aggregate: Creates methods associated with an abstract iterator class and can add methods needed by other Aggregate classes.

  • ConcreteAggregate: Implements all the methods declared by the abstract collection class. When the collection class is used ConcreteAggregate, an iterator class is created

  • Abstract Iterator class (Iterator) : defines uniform Iterator methods hasNext() and next() to determine whether there are still objects in the current collection and to read the current objects in the collection in order.

  • ConcreteIterator: Implements the methods declared by the abstract iterator class to handle offsets of objects in concrete collections and the transfer of concrete object data.

According to this pattern combined with Java Iterator, we implement the code as follows:

// The first step is to create an interface iterator generic as well

// create abstract IteratorIterator
public interface IteratorIterator<E> {
    void reset(a);       // Reset to the first element
    E next(a);           // Get the next element
    E currentItem(a);    // Retrieve the current element
    boolean hasNext(a);  // Determine if the next element exists.
}



// Next, let's define the abstract set ListList (again to distinguish it from the List interface in Java).
// Also declared as a generic interface, takes a type parameter E, declares a method iterator() that creates IteratorIterator.

public interface ListList<E> {
    IteratorIterator<E> iterator(a);
}


// Then, we construct an object called Message, which contains only the body property, its constructor, and the get and set methods.

public class Message {
    private String body;
    public Topic(String body) {
        super(a);this.body = body;
    }
    public String getBody(a) {
        return body;
    }
    public void setBody(String body) {
        this.body = body; }}Copy the code

We then implement a concrete iterator class, MessageIterator, which contains an array of properties for Message and an object position that records where the object is stored. When we execute the next() method, we get the object at the current location, reset() resets the object to 0 in the array, currentItem() returns the object at the current location, and hasNext() determines if the current location is out of bounds.


public class MessageIterator implements IteratorIterator<Message> {
    private Message[] messages;
    private int position;
    public MessageIterator(Message[] messages) {
        this.messages = messages;
        position = 0;
    }
    @Override
    public void reset(a) {
        position = 0;
    }
    @Override
    public Message next(a) {
        return messages[position++];
    }
    @Override
    public Message currentItem(a) {
        return messages[position];
    }
    @Override
    public boolean hasNext(a) {
        if(position >= messages.length) {
            return false;
        }
        return true; }}Copy the code

Also, you need to implement a concrete collection class, MessageList, that implements only one method that creates an iterator and returns the class method that corresponds to the specific iterator.


public class MessageList implements ListList<Message>{
    private Message[] messages;
    public MessageList(Message[] messages)
    {
        this.messages = messages;
    }
    @Override
    public IteratorIterator<Message> iterator(a) {
        return newMessageIterator(topics); }}Copy the code
// Unit test
public class Client {
    public static void main(String[] args) {
        
        // Define the message body to hold three messages
        Message[] messages = new Message[5];
        messages[0] = new Topic("topic1");
        messages[1] = new Topic("topic2");
        messages[2] = new Topic("topic3");
        ListList<Message> list = new MessageList(messages);
        
        // Iterator loop
        IteratorIterator<Message> iterator = list.iterator();
        while(iterator.hasNext()) { Message currentTopic = iterator.next(); System.out.println(currentTopic.getBody()); }}}// Output the result
topic1
topic2
topic3
Copy the code

OK, that’s the end of the code, and we can see that the principle is relatively simple. That is, access to objects in a collection is unified by creating a uniform Iterator for objects in the collection

conclusion

Why use the iterator pattern?

  • First, reduce repeated traversal code in the program.

  • Second, to hide the method logic of the unified traversal set. The iterator pattern abstracts the access logic of different collection classes. In this way, the algorithms needed for traversal of different collections can be hidden without exposing the internal structure of the collection, and at the same time, it can provide a simpler access algorithm interface.

Advantages:

1. You can reduce the problem of repeated code using for loops directly

2. Meet the open and close principle. When a new collection of objects needs to be extended, it can be easily extended by adding concrete object iterators and concrete collection classes.

Disadvantages:

A. Increase the number of subclasses. When you add an iterator for a collection type, you also have to add an iterator for that type and a collection object, which adds many different subclasses

overtones

Thank you for reading, and if you feel you’ve learned something, please like it and follow it.

I have included this chapter in my project, click on the project below, and follow the column. I will publish dry items every day, and I will continue to enter design patterns this month.

Come on! See you next time!