loading...

Design Pattern: The Iterator and Composite Patterns

danlee0528 profile image Daniel Lee ・2 min read

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.

Posted on by:

danlee0528 profile

Daniel Lee

@danlee0528

I love interactive & visual technology and playing with data.

Discussion

pic
Editor guide