Design Mode-iterator Mode

Source: Internet
Author: User

Design Mode-iterator Mode
Overview

In software development, we often need to use aggregate objects to store a series of data. Aggregation objects have two responsibilities: one is to store data, and the other is to traverse data. From the perspective of dependency, the former is the basic responsibility of aggregation objects, while the latter is changeable and detachable. Therefore, we can separate the traversal data from the aggregate object and encapsulate it in an object called an iterator, the iterator is used to traverse the internal data of an aggregate object, which simplifies the design of the aggregate object and better meets the requirements of the "single responsibility principle.

Definition

The iterator mode is defined as follows:

Iterator Pattern: provides a method to access an aggregate object without exposing its internal representation. Its alias is Cursor ). The iterator mode is an object behavior mode.

Iterator mode structure

The iterator mode structure contains two layers: Aggregation and iterator. Considering the flexibility and scalability of the system, the factory method mode is applied in the iterator mode. Its pattern structure is shown in Figure 3:

The iterator mode structure includes the following roles:
● Iterator (Abstract Iterator): it defines interfaces for accessing and traversing elements and declares methods for Traversing data elements. For example, it is used to obtain the first () method of the first element, the next () method used to access the next element, used to determine whether there is another hasNext () method of the next element, used to obtain the currentItem () method of the current element, etc, these methods will be implemented in a specific iterator.
● ConcreteIterator (Specific iterator): it implements an abstract iterator interface to traverse aggregate objects, at the same time, the cursor is used in a specific iterator to record the current position in the aggregation object. In actual implementation, the cursor is usually a non-negative integer that represents the position.
● Aggregate (Abstract aggregation class): it is used to store and manage element objects and declares a createIterator () method to create an iterator object and act as the abstract iterator factory role.
● ConcreteAggregate (specific aggregation class): it implements the createIterator () method declared in the abstract aggregation class. This method returns a concrete ConcreteIterator instance corresponding to the specific aggregation class.

In the iterator mode, an external iterator is provided to access and traverse aggregate objects. The iterator defines an interface to access the aggregate element, in addition, you can track the elements currently traversed to find out which elements have been traversed and which have not. The introduction of the iterator will simplify the operation on a complex aggregate object.

Typical code of the iterator Mode

The following code is used to further analyze the structure of the iterator mode. The factory method mode is applied in the iterator mode. The abstract iterator corresponds to the abstract Product role, the specific iterator corresponds to the specific product role, and the abstract aggregation class corresponds to the abstract factory role, A specific aggregation class corresponds to a specific factory role.

The abstract iterator defines the method used to traverse elements stored in the aggregate object. The typical code is as follows:

Interface Iterator {public void first (); // points the cursor to the first element public void next (); // points the cursor to the next element public boolean hasNext (); // determine whether the next element public Object currentItem () exists; // obtain the current element pointed to by the cursor}

The following code implements the data Traversal method declared by the abstract iterator in a specific iterator:

Class ConcreteIterator implements Iterator {private ConcreteAggregate objects; // maintain a reference to a specific aggregate object to facilitate access to the data private int cursor stored in the aggregate object; // defines a cursor, used to record the current access location public ConcreteIterator (ConcreteAggregate objects) {this. objects = objects;} public void first (){......} public void next (){......} public boolean hasNext (){......} public Object currentItem (){......}}

It should be noted that the design of the abstract iterator interface is very important. On the one hand, we need to fully meet the requirements of various traversal operations, provide declarations for all kinds of traversal methods as much as possible, and on the other hand, it cannot contain too many methods, too many methods in the interface will cause trouble for the implementation of sub-classes. Therefore, you can consider using an abstract class to design an abstract iterator and provide an empty default implementation for each method in the abstract class. If you need to add a new traversal operation for the aggregate object in a specific iterator, you must modify the source code of the abstract iterator and the specific iterator, which violates the "open and closed principle ", therefore, it is necessary to consider all aspects during the design to avoid modifying the interface later.

The aggregation class is used to store data and create iterator objects. The simplest abstract aggregation class code is as follows:

interface Aggregate {      Iterator createIterator();  }  

A specific aggregation class is a subclass of an abstract aggregation class. It stores data and implements the createIterator () method declared in the abstract aggregation class (), return a specific iterator object corresponding to the specific aggregation class. The Code is as follows:

class ConcreteAggregate implements Aggregate {        ......        public Iterator createIterator() {      return new ConcreteIterator(this);      }      ......  }
Implement iterator using internal classes

In the iterator mode structure, we can see that there is a dual relationship between the specific iterator class and the specific aggregation class, one of which is the association relationship, in a specific iterator, you need to maintain a reference to a specific aggregate object. The association aims to access the data stored in the aggregate object so that the iterator can traverse the data.

In addition to associations, to allow the iterator to access the data in the aggregation object, we can also design the iterator class as an internal class of the aggregation class, the iterator class in JDK is implemented in this way, as shown in the following snippet of the javasactlist class code:

package java.util;  ……  public abstract class AbstractList
  
    extends AbstractCollection
   
     implements List
    
      {      ......      private class Itr implements Iterator
     
       {          int cursor = 0;          ......      }      ...... } 
     
    
   
  
JDK built-in iterator

To make it easier for developers to operate aggregate objects, a built-in iterator is provided in Java, C #, and other programming languages. In the Java Collection framework, common aggregate classes such as List and Set inherit (or implement) the java. util. Collection interface, and the following method (Part) is declared in the Collection interface ):

package java.util;  public interface Collection
  
    extends Iterable
   
     {      ……  boolean add(Object c);  boolean addAll(Collection c);  boolean remove(Object o);  boolean removeAll(Collection c);  boolean remainAll(Collection c);   Iterator iterator();  ……  } 
   
  

In addition to adding and deleting elements, an iterator () method is provided to return an Iterator iterator object to traverse the elements in the aggregation; A specific Java aggregation class can return a specific iterator object by implementing the Iterator () method.

JDK defines the Iterator interface of the abstract Iterator. The Code is as follows:

package java.util;  public interface Iterator
  
    {  boolean hasNext();  E next();  void remove();  }
  

HasNext () is used to determine whether the next element exists in the aggregate object. To avoid throwing an exception, you must call hasNext () before each call to next (), if an element is accessible, true is returned. The next () method is used to move the cursor to the next element, through which the elements in the aggregation can be accessed one by one, it returns the reference of the element crossed by the cursor. The remove () method is used to delete the element returned when next () is called last time.

Summary

The iterator mode is a design mode with a very high usage frequency. By introducing the iterator, the data traversal function can be separated from the aggregate object, and the aggregate object is only responsible for storing data, the iterator is used to traverse data. Because many programming language libraries have already implemented the iterator mode, in actual development, we only need to directly use the already defined iterator in Java, C #, and other languages, the iterator has become one of the basic tools for operating aggregate objects.

Advantages

The main advantages of the iterator mode are as follows:
(1) It supports traversing an aggregate object in different ways, and multiple traversal methods can be defined on the same aggregate object. In the iterator mode, you only need to replace the original iterator with a different iterator to change the traversal algorithm. You can also define the subclass of the iterator to support the new Traversal method.
(2) The iterator simplifies the aggregation class. Since the iterator is introduced, you do not need to provide data traversal and other methods in the original aggregate object, which can simplify the design of the aggregation class.
(3) In the iterator mode, the introduction of the abstract layer makes it easy to add new aggregate classes and iterator classes without modifying the original code, meets the requirements of the "Open and closed principle.

Disadvantages

The main disadvantages of the iterator mode are as follows:
(1) because the iterator mode separates the responsibilities of data storage from the traversal data, a new aggregation class needs to be added corresponding to the new iterator class, and the number of classes increases in pairs, this increases the complexity of the system to a certain extent.
(2) It is difficult to design the abstract Iterator, and the future extension of the system must be fully taken into account. For example, the built-in JDK Iterator cannot implement reverse traversal. If reverse traversal is required, the ListIterator iterator can only be implemented by its subclass ListIterator. The ListIterator iterator cannot be used to operate Set-type aggregate objects. It is not easy to create a fully-considered abstract iterator when customizing the iterator.

Applicable scenarios

The iterator mode can be considered in the following cases:
(1) access the content of an aggregate object without exposing its internal representation. Separating access to aggregated objects from storage of internal data makes it unnecessary to understand the internal implementation details when accessing aggregated objects.
(2) Multiple traversal methods must be provided for an aggregate object.
(3) provides a unified interface for Traversing different aggregation structures, and provides different traversal methods for different aggregation structures in the interface implementation class, the client can operate on this interface in a consistent manner.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.