Iterator Pattern

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation

Iterator Pattern Diagram


  • To access an aggregate object's contents without exposing its internal representation
  • To support multiple traversals of aggregate objects.
  • To provide a uniform interface for traversing different aggregate structures


Let's take a pretty simple example application in which we have a collection of libraries. We need to provide a way for this collection to create a iterator on demand. Hence, client code can just rely on simple interface defined by iterator to take iterate through the collection and take further action if needed. First, Let's define an Iterator interface

Iterator Interface

Next, we would need to define a collection interface and implement a concrete collection on which we create a iterator on demand

Iterator Collection

And finally, we would glue iterator and collection together by implement a sample library iterator as below

Iterator Implementation

Eventually, we have it - the Iterator Pattern implemented in Go. This pattern provides an flexibility on independent development of client code, collection and iterator. Real life example would be how different recommendation tour guides to help you visit all attractive destinations in the city

P/s: The accompany code is included in this PR 😊

Happy coding 😎