Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Go

Go

Simple, fast to compile, built for concurrent network services.

Paradigm
Procedural, composition over inheritance
Typing
Static, strong, structural interfaces
Memory
Concurrent low-latency GC
Runs
Single static native binary
Concurrency
Goroutines and channels
Structural pattern

Composite

Intent

Composes objects into tree structures and lets clients treat individual objects and compositions uniformly.

Problem

An order contains products and boxes, and boxes contain more boxes. Computing the total price is messy.

Solution

Leaves and containers share one interface; containers delegate to children and aggregate results.

Real-world analogy

Think of it like this

An army: orders go from generals to divisions, to squads, to soldiers. Everyone receives an order the same way.

Structure

association / extends implements / depends on
Client 4 «interface» Component + execute() 1 Leaf + execute() 2 Composite - children: Component[]+ add(c: Component)+ remove(c: Component)+ execute() 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Component — Component declares operations common to simple and complex elements of the tree.
  2. 2Leaf — Leaf is a basic element that does the actual work.
  3. 3Composite — Composite (container) holds children, delegates work to them and combines the results.
  4. 4Client — Client works with every element through the Component interface.

Code example

A Go code sample for Composite is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Composite when you need a tree-like object structure.

Use Composite when clients should treat simple and complex elements the same way.

Pros and cons

Pros

  • Polymorphism and recursion over trees
  • New element types without breaking code

Cons

  • A common interface can become over-general

Relations with other patterns

Check yourself

Check yourself

A file explorer must compute the size of a folder that contains files and other folders.

Saved in this browser only. Part of Structural patterns (0/7).