Video in progress

Strong Middle 🧱 OOP and SOLID

What is the Composite pattern and how does it help model tree-like structures (categories, menus, org charts)?

In Composite, a single element and a group of elements implement the same interface. Client code then doesn't ask "is this a leaf or a branch?": it calls total() or render(), and the group passes the call down to its children recursively.

📖 Answer

An example is priced collections: a single product and a bundle of products, where a bundle can contain other bundles.

public sealed interface CatalogItem permits Product, Bundle {
    Money price();
}

public record Product(String sku, Money price) implements CatalogItem {}

public record Bundle(String name, List<CatalogItem> items, int discountPercent)
        implements CatalogItem {
    public Bundle { items = List.copyOf(items); }

    public Money price() {
        Money sum = items.stream().map(CatalogItem::price).reduce(Money.ZERO, Money::plus);
        return sum.minusPercent(discountPercent);
    }
}

For the cart code there's no difference: item.price(). Nested bundles work automatically too.

What I watch for in practice:

  • Cycles. If a bundle contains itself (even indirectly), you get infinite recursion. Check on creation or on save.
  • Depth and the DB. Loading a category tree recursively in JPA with @OneToMany children gives N+1 queries. Often it's faster to load the whole tree in one query (a recursive CTE, or fetching everything by parent_id) and build it in memory.
  • Operations that only make sense for a group (add, remove) should not go on the common interface: they're meaningless for a leaf and break LSP.

Composite often comes together with Visitor or pattern matching, for different computations over the tree (price, weight, export).