Skip to the guide

Composite

IntermediatePattern7 pages

Composite lets a single item and a group answer the same call, so a group can hold other groups to any depth and callers never ask which one they hold. The 1994 book Design Patterns gives its intent as "compose objects into tree structures to represent part-whole hierarchies." Interviewers listen for where add and remove live, and for when a plain set of names is enough.

Playlists inside playlists

Think of a music app where a playlist can hold songs and other playlists. Your party playlist holds a few songs and your friend's whole 80s playlist as one entry. Ask any entry "is this song in you?" and you get an answer. A song checks itself, and a playlist asks its entries, the 80s playlist included. When your friend adds a song to her list, the party has it too, because it holds her playlist, not a copy of its songs. You can add a song to a playlist, but nobody adds anything to a song.

In code, a song is a User, one person, and a playlist is a Group, which holds users and other groups. The question every entry answers is includes(user), written in the Member interface, which both classes implement. The party playlist is the editors group, and the friend's playlist inside it is the design team. Whoever presses play is the shared Folder, which asks its one member and never asks whether it is a person or a group.