05 / 10

Composite Pattern

Difficulty: 5/10
tree structures, uniform interface, object composition

The Composite pattern composes objects into tree structures to represent part-whole hierarchies, allowing clients to treat individual objects and compositions uniformly.

The Composite pattern is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects. This pattern is fundamental to React's component-based architecture, where components can contain other components, forming a tree structure [citation:7].

Vanilla JavaScript Implementation
React Implementation
Angular Implementation

Scenario Questions

0-2 years experience

  1. 1We have a UI where both buttons and panels need a draw() method. How would you organize the classes using the Composite pattern?
  2. 2If you call addChild on a leaf widget that doesn't support children, what behavior is expected and why?
  3. 3Imagine a file‑system model where files and directories both need a getSize() call. Sketch the class hierarchy using Composite.

2-5 years experience

  1. 1While adding a new submenu to our navigation tree, we hit a NullPointerException when iterating children. How would you debug this in a Composite implementation?
  2. 2We now need to serialize the component tree to JSON as well as render it. What trade‑offs does the Composite pattern introduce compared to adding a separate Visitor?
  3. 3If a new operation like exportToPDF must be added without touching existing leaf and composite classes, how would you extend the design?

5-8 years experience

  1. 1Our UI component Composite has grown to thousands of nodes and rendering is slow. How would you redesign or optimize the hierarchy for better performance?
  2. 2The component tree can be reconfigured at runtime by multiple services. What concurrency issues arise with the Composite pattern and how would you mitigate them?
  3. 3Third‑party widgets don’t implement our Component interface. How can you integrate them without breaking the existing Composite structure?

8+ years experience

  1. 1A legacy monolith uses a Composite for permission hierarchies, and we’re moving to microservices. How would you evolve the pattern to support distributed enforcement while preserving a uniform API?
  2. 2Different teams have diverged on the Component interface version. What strategy would you use to establish a shared contract and migrate safely?
  3. 3If we decide to replace the Composite with an Entity‑Component‑System for scalability, what migration steps and trade‑offs should we consider?

Follow-up Questions

  • What would you change if you needed to add a new operation to all components?
  • How does the pattern affect testing of leaf versus composite objects?
  • Can you compare Composite with the Visitor pattern in this context?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.