DEV Community

Daniel Lee
Daniel Lee

Posted on


Design Pattern: The Iterator and Composite Patterns

The Iterator Pattern

It provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It places the task of traversal of the iterator object not on the aggregate, which simplifies the aggregate interface and implementation, and places the responsibility where it should be.

There are two types of iterators: external and internal

  1. External iterator is used for clients to control the iteration by calling next() to get the next element.
  2. Internal iterator is controlled by the iterator itself; pass an operation to an iterator as it steps through the element.

No matter which iterator you end up using, iterators can be made up of many different data structures such as array, linked list, etc.

This property of the pattern impose single responsibility for each class: a class should have only one reason to change.

Composite Pattern

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and composition of objects uniformly.

In much simpler sentence, it allows us to build structures of objects in the form of trees that contain both compositions of objects and individual objects as nodes.

Using a composite structure, we can apply the same operations over both composites and individual objects. In most cases, we can ignore the differences between compositions of objects and individual object.

The Composite Pattern takes the single responsibility design principle and trades it for transparency.

  • By allowing the component interface to contain the child management operations and the leaf operations, a client can treat both composites and leaf node uniformly.
    • A Component is any object in a composite structure. Components may be other composites or leaf nodes.

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git