ProgramGuru

Composite Pattern

Composite: start from the problem

See the responsibilities

ClientCalls total
BundleDelegates to children
Leaf or bundleUses the same operation
ResultCombines child totals
Client: Calls total → Bundle: Delegates to children → Leaf or bundle: Uses the same operation → Result: Combines child totals

A price estimator handles an individual item and a bundle of items. Bundles can contain smaller bundles. Special-casing every nesting level makes the traversal difficult to extend.

This is a structural pattern lesson. Follow the responsibilities, inspect the small JavaScript example and compare the design choices. The example is local teaching code; its boundary is explained before you apply the idea to a real service.

What you’ll learn

  • Explain the problem Composite addresses and the roles involved.
  • Follow the example and distinguish this pattern from nearby alternatives.
  • Choose when the benefit justifies the extra responsibilities and testing.

How the responsibilities work

Composite gives individual leaves and groups a common operation. A group delegates that operation to its children and combines the results. Clients can use the operation without knowing whether they received one leaf or a whole tree.

The example uses total for both items and bundles. A nested bundle computes the sum recursively. The common interface is useful only when its meaning is sensible for both leaf and group.

Follow a small example

Read the JavaScript from top to bottom and compare the expected output. The values are chosen to make this pattern’s responsibility visible. This example runs in one local execution context; it does not create remote services, durable storage or production access controls.

JavaScript · local teaching example

const item = price => ({total: () => price});
const bundle = children => ({total: () => children.reduce((sum, child) => sum + child.total(), 0)});
const order = bundle([item(10), bundle([item(5), item(3)])]);
console.log(order.total());

Expected output

18

Choose a design and inspect the consequence

Compare the design choices

A bundle accidentally includes itself.
A leaf cannot meaningfully remove children.

Compare the visible consequences. With JavaScript enabled, choose an option in each scenario to assemble your decision record.

This is an exploratory design exercise. It does not run infrastructure, measure capacity or replace the lesson’s quiz.

Use the consequences to explain your decision, including the simpler alternative.

Apply the pattern to two situations. Select one option in each situation to build a decision record. Every option and its consequence stays visible, and you can change your choices.

When it helps—and what it costs

Use it for naturally nested structures such as menus, folders or expression trees when shared operations have a clear meaning.

Prevent accidental cycles and unreasonable nesting depth. A generic interface can expose operations that make no sense on leaves. Decide whether repeated child references represent shared objects or repeated counted items.

Distinguish the neighbouring patterns

Decorator wraps an object to add behaviour rather than treating children as one group. Visitor can add operations across an existing Composite node family.

Follow Decorator’s behaviour wrappers, Visitor operations on node families, Iterator traversal to compare the specific responsibility before combining patterns.

Check your pattern reasoning

Why can the client call total on a bundle or an item?
Choose one answer. You can try again.

Answer and explanation

Both expose the same meaningful operation.

The group delegates and combines child totals.

Check your pattern reasoning

What can break a naive recursive composite?
Choose one answer. You can try again.

Answer and explanation

Cycles or excessive nesting.

Traversal needs a deliberate structure and limits.

Name the responsibility before choosing the pattern

For Composite, describe the problem, the participating roles and the observable contract. Use the example as a starting point and test the boundaries identified in the trade-offs. A pattern name alone does not establish correctness or performance.

Return to the design-pattern guide to compare families, or apply the idea alongside Iterator traversal.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Decorator Pattern →