Design Patterns Explained
  • Getting Started
  • SOLID Principles
    • Single Responsibility Principle
    • Open / Closed Principle
    • Liskov Substitution Principle
    • Interface Segregation Principle
    • Dependency Inversion Principle
  • Design Patterns
    • Creational Patterns
      • Abstract Factory Pattern
      • Builder Pattern
      • Factory Pattern
      • Prototype Pattern
      • Singleton Pattern
    • Behavioral Patterns
      • Chain Of Responsibility Pattern
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
        • Example 1
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
        • Example 1
      • Template Method Pattern
      • Visitor Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Decorator Pattern
      • Facade Pattern
      • Flyweight Pattern
      • Proxy Pattern
  • Roadmap
Powered by GitBook
On this page
  • Intent
  • When to use
  • Structure
  • Notes
  • Examples

Was this helpful?

  1. Design Patterns
  2. Behavioral Patterns

Iterator Pattern

PreviousInterpreter PatternNextMediator Pattern

Last updated 4 years ago

Was this helpful?

Intent

Provide a way to access the elements of a collection without exposing the underlying representation.

When to use

  1. When your collection has a complex data structure under the hood, but you want to hide its complexity from clients (either for convenience or security reasons).

  2. To support multiple traversal techniques for a collection.

  3. You want to provide a uniform interface for traversing different types of collections (Polymorphic Iteration).

  4. To reduce duplication of the traversal code across your app.

Structure

  • Iterator: defines an interface for accessing and traversing elements.

  • ConcreteIterator: implements the iterator interface for a certain collection.

  • IterableCollection: defines an interface for creating an iterator object.

  • ConcreteCollection: keeps track of the current object (data structure).

Notes

Most of the programming languages provide their own ways of implementing iterators. TypeScript (and JS of course) provide an interface for the Iterators, and a Symbol in the class to create the iterators so the Collection will be able to participate in for..of loops (check example 2 and 3). Also generator functions return iterators so they can be used as iterators (Check example 3).

Examples

Source Code

UML

// TODO

// TODO

// TODO

You can find the tests .

here
Example 1
Example 2
Example 3