7
Back to Boss Battles

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.

Rendering diagram…

The Core Difference

AspectCompositeDecorator
PurposeModel part-whole tree hierarchiesAdd behavior to an individual object
StructureOne parent, many children (tree)One wrapper, one wrapped (chain)
ChildrenHolds a collection of componentsHolds exactly one component
TraversalRecurse through tree to aggregateChain through wrappers to enhance
IdentityA folder IS-A collection of filesA cached handler IS-A handler with caching
Operationsadd(), remove(), getChild()Only wraps operation()
Real-worldFile system, org chart, menu treeMiddleware 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

typescript
1interface PermissionNode {
2 getPermissions(): Set<string>;
3}
4
5class 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
16class 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
35const admins = new Group('admins');
36admins.add(new User('alice', ['read', 'write', 'delete']));
37const subgroup = new Group('editors');
38subgroup.add(new User('bob', ['read', 'write']));
39admins.add(subgroup);
40admins.getPermissions(); // { read, write, delete }

Decorator β€” Handler middleware stack

typescript
1interface RequestHandler {
2 handle(req: Request): Promise<Response>;
3}
4
5class 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
12class 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
23class 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
37const handler = new CachingDecorator(
38 new LoggingDecorator(
39 new ApiHandler()
40 )
41);

Decision Rules

SignalChooseWhy
Part-whole hierarchy (contains children of same type)CompositeTree traversal with uniform interface
Add behavior to an object without changing itDecoratorWrap and enhance
Need add/remove/getChild operationsCompositeManaging a tree
Need to stack enhancements in any orderDecoratorChain of wrappers
Compute aggregate across tree (total price, all permissions)CompositeRecursive aggregation
File system, org chart, menu, permission groupsCompositeNatural tree structures
Middleware, logging, caching, compression wrappersDecoratorBehavior 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.