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.
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.
import java.util.ArrayList;
import java.util.List;
public class CompositeShapes {
interface Shape { void draw(String indent); }
static class Circle implements Shape {
public void draw(String indent) { System.out.println(indent + "Circle"); }
}
static class Square implements Shape {
public void draw(String indent) { System.out.println(indent + "Square"); }
}
static class Group implements Shape {
private final String name;
private final List<Shape> children = new ArrayList<>();
Group(String name) { this.name = name; }
Group add(Shape s) { children.add(s); return this; }
public void draw(String indent) {
System.out.println(indent + "Group " + name);
for (Shape s : children) s.draw(indent + " "); // same call for leaf or group
}
}
public static void main(String[] args) {
Group logo = new Group("logo").add(new Circle()).add(new Square());
Group page = new Group("page").add(logo).add(new Circle());
page.draw("");
}
}Group page
Group logo
Circle
Square
Circle
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.
Last updated: 1 November 2026
Previous question: What are the key benefits of using the Bridge pattern in large systems?
Next question: Can you provide an example of how the Composite pattern can be used to model tree structures?