Design Patterns - Iterator Pattern(19)

definition

Iterator Pattern is one of the most frequently used patterns and is widely used in Java APIs. For example, in the Java Collection framework, iterators are widely used to traverse the elements in the collection.

英文原话:Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Translation: Provides a way to access elements in a container object without exposing the internal details of the object.

The iterator serves the container, and the container refers to the object used to hold other objects, such as Collection type, Set type, etc. The iterator pattern facilitates traversing and accessing elements in a container.

Role:

Abstract Iterator role: This role is responsible for defining the interface for accessing and traversing elements.

Concrete Iterator role: This role implements the Iterator interface to complete the traversal of container elements.

Abstract Aggregate role: This role provides an interface for creating iterator roles.

Concrete Aggregate role: This role implements the abstract aggregate interface and creates objects that hold iterators.

 

advantage

  • The iterator mode simplifies the operation of accessing container elements and has a unified traversal interface.
  • Encapsulates the traversal algorithm, making the algorithm independent of the aggregation role. The client does not need to know the type of the aggregate object, even if the type of the aggregate object changes, it will not affect the traversal process.

shortcoming

  • The iterator pattern gives the user an illusion of serialization, which leads to errors.
  • The elements of the iterator are all of type Object and have no type characteristics (the introduction of generics after JDK1.5 can solve this problem).

Application scenarios

The iterator pattern is now widely used and has even become a basic tool. Some people have suggested removing iterators from the 23 pattern because the iterator pattern is so common that it has been incorporated into various languages ​​and tools. In the Java language, since the JDK1.2 version, the java.util.Iterator interface has been added, and iterator has been applied to each collection class (Collection), such as ArrayList, Vector, Stack, HashSet and other collection classes have implemented iterator () method, returns an iterator Iterator, which is convenient for traversing the elements in the collection. It is also because Java has integrated the iterator pattern into the most basic API, programmers no longer need to write iterators independently in the project, they can use it directly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324680723&siteId=291194637
Recommended