The Composite pattern is a structural pattern that composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and groups of objects through the same interface.
Key Points: • Both leaf nodes and composite (container) nodes implement a common component interface. • Clients can call the same operations on a single object or an entire tree without special-casing either. • It simplifies client code by removing the need to distinguish between "one item" and "a collection of items." • Operations on a composite typically recurse into its children automatically. • It's most useful whenever data naturally forms a recursive, tree-like part-whole structure.
Example: In a graphics editor, a Shape interface might be implemented by both individual shapes like Circle and by a Group that contains other Shapes, so calling draw() on a Group automatically draws every shape it contains, nested groups included.
Interview Tip: A concise interview answer is:
"Composite lets you treat individual objects and compositions of objects uniformly through a shared interface, which is most useful for tree-like part-whole structures such as file systems or UI components, where you want operations like render or calculate-total to work the same whether you're looking at one item or a whole subtree."