Design Pattern: Iterator Pattern

Tram Ho

I. Introduction:


Iterator is a Design Pattern of the Behavior type. It allows us to browse the elements of a collection without revealing its detailed implementations. Iterator Pattern consists of the following components:

  • IterableProtocol in Swift defines a data type that allows access to elements through the for loop.
  • Iterator Object : Object is customized so that data can be accessed in a loop .

II. How it works:


Iterator Pattern provides a sequential way to access elements of a collection . The way we access this will be determined by the data structure of the collection . Data structure can be Array, Tree, … At the same time, its data access method will be concealed and not exposed to the outside.

III. When is the pattern iterator used?


Iterator Pattern is used when there is a class or structure containing a group of objects that are arranged and want to access elements using the for loop.

IV. For example:


To make it easier to access and understand, we will use the Queue data structure as an example of the Iterator Pattern . The Queue in the example will act as the Iterator Object .

Implement adopt Sequence protocol to convert Queue to Iterator form.

Add elements to Queue .

Retrieve element in Queue

V. References:


Share the news now

Source : Viblo