CompositeVSDecorator
The Problem
Scenario A β Composite territory: Your permission system has users, groups, and nested sub-groups. A group's effective permissions are the union of all its members' permissions. You need to traverse the tree and compute permissions uniformly β whether it's a single user or a deeply nested group.
Scenario B β Decorator territory: Your HTTP handler works, but you need to add request logging, response caching, and rate limiting. Each addition wraps the handler, adding behavior without modifying it. You want to stack them in any order.
Why They Look Alike
Both have recursive structure β a component that references other components of the same type. Both implement the same interface. The class diagrams are strikingly similar.
The Core Difference
| Aspect | Composite | Decorator |
|---|---|---|
| Purpose | Model part-whole tree hierarchies | Add behavior to an individual object |
| Structure | One parent, many children (tree) | One wrapper, one wrapped (chain) |
| Children | Holds a collection of components | Holds exactly one component |
| Traversal | Recurse through tree to aggregate | Chain through wrappers to enhance |
| Identity | A folder IS-A collection of files | A cached handler IS-A handler with caching |
| Operations | add(), remove(), getChild() | Only wraps operation() |
| Real-world | File system, org chart, menu tree | Middleware stack, stream pipes |
One sentence: Composite builds trees (many children); Decorator wraps chains (one wrapped object, enhanced behavior).
Side-by-Side Code
Composite β Permission tree
| 1 | interface PermissionNode { |
| 2 | getPermissions(): Set<string>; |
| 3 | } |
| 4 | |
| 5 | class User implements PermissionNode { |
| 6 | constructor( |
| 7 | private name: string, |
| 8 | private perms: string[], |
| 9 | ) {} |
| 10 | |
| 11 | getPermissions(): Set<string> { |
| 12 | return new Set(this.perms); |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | class Group implements PermissionNode { |
| 17 | private members: PermissionNode[] = []; |
| 18 | |
| 19 | constructor(private name: string) {} |
| 20 | |
| 21 | add(member: PermissionNode): void { |
| 22 | this.members.push(member); |
| 23 | } |
| 24 | |
| 25 | getPermissions(): Set<string> { |
| 26 | const all = new Set<string>(); |
| 27 | for (const m of this.members) { |
| 28 | for (const p of m.getPermissions()) all.add(p); |
| 29 | } |
| 30 | return all; // union of all children |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // Usage: tree structure |
| 35 | const admins = new Group('admins'); |
| 36 | admins.add(new User('alice', ['read', 'write', 'delete'])); |
| 37 | const subgroup = new Group('editors'); |
| 38 | subgroup.add(new User('bob', ['read', 'write'])); |
| 39 | admins.add(subgroup); |
| 40 | admins.getPermissions(); // { read, write, delete } |
Decorator β Handler middleware stack
| 1 | interface RequestHandler { |
| 2 | handle(req: Request): Promise<Response>; |
| 3 | } |
| 4 | |
| 5 | class ApiHandler implements RequestHandler { |
| 6 | async handle(req: Request): Promise<Response> { |
| 7 | const data = await this.db.query(req.params.id); |
| 8 | return { status: 200, body: data }; |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | class LoggingDecorator implements RequestHandler { |
| 13 | constructor(private wrapped: RequestHandler) {} |
| 14 | |
| 15 | async handle(req: Request): Promise<Response> { |
| 16 | console.log(`β ${req.method} ${req.url}`); |
| 17 | const res = await this.wrapped.handle(req); // always delegates |
| 18 | console.log(`β ${res.status}`); |
| 19 | return res; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | class CachingDecorator implements RequestHandler { |
| 24 | private cache = new Map<string, Response>(); |
| 25 | constructor(private wrapped: RequestHandler) {} |
| 26 | |
| 27 | async handle(req: Request): Promise<Response> { |
| 28 | const key = req.url; |
| 29 | if (this.cache.has(key)) return this.cache.get(key)!; |
| 30 | const res = await this.wrapped.handle(req); |
| 31 | this.cache.set(key, res); |
| 32 | return res; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // Stack decorators β each wraps one handler |
| 37 | const handler = new CachingDecorator( |
| 38 | new LoggingDecorator( |
| 39 | new ApiHandler() |
| 40 | ) |
| 41 | ); |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| Part-whole hierarchy (contains children of same type) | Composite | Tree traversal with uniform interface |
| Add behavior to an object without changing it | Decorator | Wrap and enhance |
| Need add/remove/getChild operations | Composite | Managing a tree |
| Need to stack enhancements in any order | Decorator | Chain of wrappers |
| Compute aggregate across tree (total price, all permissions) | Composite | Recursive aggregation |
| File system, org chart, menu, permission groups | Composite | Natural tree structures |
| Middleware, logging, caching, compression wrappers | Decorator | Behavior stacking |
The Trick Question
"Your notification system has channels: EmailChannel, SMSChannel, and a ComboChannel that sends via multiple channels. Is this Composite or Decorator?"
This is Composite. ComboChannel holds a collection of channels and calls send() on all of them β that's a tree (one parent, many children). It would be Decorator if ComboChannel wrapped a single channel and added behavior (like adding a header before sending).
The tell: does it hold one wrapped object (Decorator) or a collection of children (Composite)?
Interview Angles
Q: Can you combine Composite and Decorator?
Yes. You can decorate a composite node. For example, a CachedPermissionGroup decorates a Group to cache the computed permissions. The decorator wraps one composite node; the composite holds many children.
Q: How do NestJS interceptors relate?
NestJS interceptors are Decorator-like β each wraps the handler and can add behavior (logging, caching, transformation) before and after. They chain through next.handle(), not through a tree.
Q: What's the risk of deep Composite trees? Performance β recursive traversal of a large tree can be slow. Circular references cause infinite loops. Always guard against cycles and consider caching aggregate results.