THN Interview Prep

Composite (Structural)

Intent / problem it solves

Compose objects into tree structures to represent part-whole hierarchies. Clients treat individual objects and compositions uniformly through a common interface.

When to use / when NOT

Use for nested menus, file systems, UI trees, org charts, or AST-like structures.

Avoid when you only have shallow lists without recursion, or when a flat structure plus IDs is simpler.

Structure

Component declares children operations; leaf has no children; composite stores child components.

Loading diagram…

Go example

package main

import (
	"fmt"
	"strings"
)

type Graphic interface {
	Draw(indent int) string
}

type Circle struct{ label string }

func (circle Circle) Draw(indent int) string {
	return strings.Repeat("  ", indent) + "circle:" + circle.label
}

type Group struct {
	label    string
	children []Graphic
}

func (group *Group) Add(child Graphic) { group.children = append(group.children, child) }

func (group Group) Draw(indent int) string {
	lines := []string{strings.Repeat("  ", indent) + "group:" + group.label}
	for _, child := range group.children {
		lines = append(lines, child.Draw(indent+1))
	}
	return strings.Join(lines, "\n")
}

func main() {
	root := Group{label: "scene"}
	root.Add(Circle{label: "sun"})
	fmt.Println(root.Draw(0))
}

JavaScript example

class Node {
  render(depth) {
    throw new Error('override');
  }
}

class TextNode extends Node {
  constructor(value) {
    super();
    this.value = value;
  }

  render(depth) {
    return `${'  '.repeat(depth)}text:${this.value}`;
  }
}

class ContainerNode extends Node {
  constructor(name) {
    super();
    this.name = name;
    this.children = [];
  }

  add(child) {
    this.children.push(child);
  }

  render(depth) {
    const header = `${'  '.repeat(depth)}group:${this.name}`;
    const body = this.children.map((child) => child.render(depth + 1));
    return [header, ...body].join('\n');
  }
}

const root = new ContainerNode('layout');
root.add(new TextNode('hello'));
console.log(root.render(0));

Interview phrase

“Composite gives one interface for leaves and containers so callers recurse without instanceof chains; I use it for menus and document models.”

Map to LLD for folder trees, nested UI, or expression evaluation in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page