Skip to content
Commitwise
Menu

Composite pattern

Single items and groups of items share one interface, so code treats a whole tree like a single item.

Definition

A leaf answers from its own data; a composite holds children of the shared interface type and answers by asking them and combining the results, recursively. New item types implement the interface instead of being added to type checks scattered through the code. Trees loaded from data need protection against cycles and very deep nesting.

In practice

A Bundle's price is the sum of its children's prices minus its discount, whether the children are products or other bundles.

Related terms

Esc

Type to search the whole site.