The Composite Pattern

Learn about the Adapter pattern and its implementation using a coding example.

We'll cover the following...

Overview

The Composite pattern allows complex tree structures to be built from simple components, often called nodes. A node with children will behave like a container; a node without children will behave like a single object. A composite object is—generally—a container object, where the content may be another composite object.

Traditionally, each node in a composite object must be either a leaf node (that cannot contain other objects) or a composite node. The key is that both composite and leaf nodes can have the same interface. The following UML diagram shows this elegant parallelism as a some_action() method:

Press + to interact
The UML diagram of the Composite pattern
The UML diagram of the Composite pattern

This simple pattern, however, allows us to create complex arrangements of elements, all of which satisfy the interface of the component object. The following diagram depicts a concrete instance of such a complicated arrangement:

Press + to interact
A large Composite pattern
A large Composite pattern

The Composite pattern applies to language processing. Both natural languages and artificial languages (like Python) tend to follow rules that are hierarchical and fit nicely with the Composite design pattern. Markup languages, like HTML, XML, RST, and Markdown, tend to reflect some common composite concepts like lists of lists, and headers with sub-headings.

A programming ...

Access this course and 1400+ top-rated courses and projects.