I went with a file system because it's the most natural fit for this pattern and I didn't want to waste time justifying a weird domain choice.
Choose a concrete domain like a file system or an organizational hierarchy to ground the pattern. Define a Component interface with common operations, then implement Leaf and Composite classes where Composite holds children and delegates recursive calls. Demonstrate with a client that builds a tree and invokes a recursive operation like size or cost.
Pro tip: Mention that the Composite pattern shines when you want clients to treat individual objects and compositions uniformly, but be aware of the trade-off: it can make your design overly general, so use it only when the part-whole hierarchy is natural.
Select a domain with a natural part-whole hierarchy, such as a file system (files and directories) or an org chart (employees and managers). Define a Component interface with operations like getSize() or getCost() that both leaves and composites will implement.
Create a Leaf class that implements the Component interface. For operations like getSize(), return the leaf's own value (e.g., file size). For composite-specific operations like add() or remove(), either throw an exception or provide a no-op, depending on the design.
Create a Composite class that also implements Component. It maintains a collection of child Components. For recursive operations like getSize(), iterate over children and sum their results. Implement add(), remove(), and getChild() to manage children.
Write a client that builds a tree of Leaf and Composite objects. Invoke a recursive operation like getSize() on the root and show how it aggregates results from all descendants. Optionally, show traversal or other operations.
Explain the benefits (uniform treatment, easy extension) and drawbacks (overly general design, difficulty restricting components). Mention variations like child management in Composite vs. Component, and caching results for performance.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.