liveBook · Manning

Composite design pattern

As explained in Object-Oriented Software Design in C++

A structural design pattern that represents part-whole hierarchies as tree structures and lets clients treat individual objects and object compositions uniformly.

The Composite Design Pattern represents part-whole hierarchies as trees and gives individual objects and object compositions a common interface. Clients can therefore process a single item or an entire group in the same way. section 14.0 section 14.2.3

The pattern organizes a hierarchy around three roles:

  • Component supplies the shared interface for individual and composite objects. section 14.2.4
  • Leaf represents an individual object, such as Ball, Bat, Glove, or Sunscreen. section 14.2.4
  • Composite contains other Components and implements operations across its children. section 14.2.3
  • Unsupported child-management operations can use default implementations that throw InvalidOperation, while composites override them. section 14.2.3

Baseball equipment cost report

A provisions hierarchy groups equipment, uniform, and footwear beneath a top-level provisions composite. Leaves hold item costs; composites calculate subtotals and print indented contents. Adding footwear beneath uniform demonstrates that nested composites work through the same interface as individual items, producing a total of $200. section 14.2 section 14.2.3

Figure 14.4 The hierarchy of objects in a tree data structure that represent the provisions for a baseball player and the cost of each item. The composite objects are shaded gray.

Use the hierarchy figure to inspect how leaf items and shaded composite groups form the provisions tree. section 14.2

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains the Component, Leaf, and Composite roles through C++ classes, virtual operations, child storage, exceptions, costing, and printing.
Examples
Uses a baseball provisions tree, item and group classes, nested footwear, subtotals, indentation, and a $200 cost report.
What it assumes
Assumes tree data structures; teaches how Component, Leaf, and Composite roles share an interface.
What you can do after
Build it from scratch by refactoring separate item and group hierarchies into a shared interface for recursive reports.
How it connects
Connects tree data structures with the Visitor Design Pattern and broader design-pattern models.

Also explained in

Compare how 4 books explain composite design pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.