# Composite

> Treat individual objects and groups of objects uniformly — client code works the same whether it's talking to a leaf or an entire tree.

- **Category**: Software Design
- **Subcategory**: structural
- **Canonical URL**: https://designpattern.fyi/patterns/composite/

---

## Description
**Intent**: Model tree structures where both individual items and collections of items should be usable interchangeably.

**Context**: You're building a file system (files and folders), UI component tree (widgets and panels), or organization chart (employees and departments). Client code shouldn't need to ask 'is this a leaf or a container?' before calling methods on it.

**Solution**: Define a Component interface with common operations (`draw()`, `getSize()`, `render()`). Leaf classes implement it directly. Composite classes implement it by delegating to their children and aggregating results. Client code calls the same methods regardless of depth in the tree.


## Use Cases
Use when you need to represent tree-like hierarchies — file systems, UI trees, menus, org charts, expression parsers — and want client code to treat leaves and branches uniformly.



## Implementation Example

```javascript
class Graphic {
  draw() {}
}

class Dot extends Graphic {
  constructor(x, y) { super(); this.x = x; this.y = y; }
  draw() { console.log(`Drawing dot at ${this.x}, ${this.y}`); }
}

class CompoundGraphic extends Graphic {
  constructor() { super(); this.children = []; }
  add(child) { this.children.push(child); }
  draw() {
    this.children.forEach(child => child.draw());
  }
}

```



## Trade-offs


### Advantages

- Client code uses one interface for the entire tree — no type-checking or special cases.

- Add new leaf or composite types without changing client code.




### Considerations & Drawbacks

- Forcing unrelated classes to share a common interface can make that interface overly generalized and awkward.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/composite)

