7
Back to Boss Battles

AdapterVSDecorator

The Problem

Scenario A — Adapter territory: You are migrating from one logging library (Winston) to another (Pino). Your codebase depends on a Logger interface with info(), warn(), error(). Pino has different method signatures. You need a wrapper that makes Pino look like your Logger.

Scenario B — Decorator territory: You have a working CacheService that reads and writes to Redis. You want to add request-level metrics (count, latency) without modifying the CacheService. You wrap it in a MetricsCacheService that measures each call and then delegates to the real one.


Why They Look Alike

Both wrap an object. Both implement the same interface as the thing they wrap (or at least appear to). Both delegate calls to an inner object. The class diagrams look almost identical.


The Fundamental Difference

Adapter changes the interface. Decorator keeps the interface and adds behaviour.

Adapter: "I need interface A, but I have interface B — translate." Decorator: "I have interface A and I want to add logging/caching/metrics to it — wrap and enhance."


Decision Rule

CluePattern
"Make this incompatible class work with our interface"Adapter
"Add behaviour without modifying the original class"Decorator
"The wrapped object has a DIFFERENT interface"Adapter
"The wrapped object has the SAME interface"Decorator
"Usually one layer of wrapping"Adapter
"Can stack multiple wrappers"Decorator
"Changes what the object IS (in terms of interface)"Adapter
"Changes what the object DOES (adds behaviour)"Decorator

Side-by-Side Code

Adapter — different interface in, your interface out

typescript
1// Your interface
2interface Logger {
3 info(msg: string): void;
4 warn(msg: string): void;
5 error(msg: string): void;
6}
7
8// Pino has a different API
9class PinoLogger {
10 child(bindings: Record<string, unknown>) { return this; }
11 // Pino uses structured logging with objects
12 info(obj: Record<string, unknown>, msg?: string) {
13 console.log(`[PINO INFO] ${msg}`, obj);
14 }
15 warn(obj: Record<string, unknown>, msg?: string) {
16 console.log(`[PINO WARN] ${msg}`, obj);
17 }
18 error(obj: Record<string, unknown>, msg?: string) {
19 console.log(`[PINO ERROR] ${msg}`, obj);
20 }
21}
22
23// Adapter: makes Pino conform to our Logger interface
24class PinoAdapter implements Logger {
25 constructor(private pino: PinoLogger) {}
26
27 info(msg: string) { this.pino.info({}, msg); }
28 warn(msg: string) { this.pino.warn({}, msg); }
29 error(msg: string) { this.pino.error({}, msg); }
30}
31
32// Usage
33const logger: Logger = new PinoAdapter(new PinoLogger());
34logger.info("Server started"); // works with our interface

Decorator — same interface, added behaviour

typescript
1interface CacheService {
2 get(key: string): Promise<string | null>;
3 set(key: string, value: string, ttl?: number): Promise<void>;
4}
5
6class RedisCacheService implements CacheService {
7 async get(key: string) {
8 console.log(`Redis GET ${key}`);
9 return "cached-value";
10 }
11 async set(key: string, value: string, ttl?: number) {
12 console.log(`Redis SET ${key} = ${value} (ttl: ${ttl})`);
13 }
14}
15
16// Decorator: same interface, adds metrics
17class MetricsCacheDecorator implements CacheService {
18 constructor(private inner: CacheService) {}
19
20 async get(key: string) {
21 const start = performance.now();
22 const result = await this.inner.get(key);
23 const ms = performance.now() - start;
24 console.log(`[METRICS] cache.get ${key} took ${ms.toFixed(1)}ms`);
25 return result;
26 }
27
28 async set(key: string, value: string, ttl?: number) {
29 const start = performance.now();
30 await this.inner.set(key, value, ttl);
31 const ms = performance.now() - start;
32 console.log(`[METRICS] cache.set ${key} took ${ms.toFixed(1)}ms`);
33 }
34}
35
36// Decorator: adds logging
37class LoggingCacheDecorator implements CacheService {
38 constructor(private inner: CacheService) {}
39
40 async get(key: string) {
41 console.log(`[LOG] GET ${key}`);
42 return this.inner.get(key);
43 }
44
45 async set(key: string, value: string, ttl?: number) {
46 console.log(`[LOG] SET ${key}`);
47 return this.inner.set(key, value, ttl);
48 }
49}
50
51// Stack decorators — this is the power of Decorator
52const cache: CacheService = new LoggingCacheDecorator(
53 new MetricsCacheDecorator(
54 new RedisCacheService()
55 )
56);
57cache.get("user:123"); // logged → timed → Redis

Key difference: Adapter translates between interfaces. Decorator wraps the same interface to add behaviour, and you can stack them.


Scenario Quiz

?Knowledge Check

1You wrap an Express request object to match your framework's Request interface. Which pattern?

2You wrap a UserRepository to add caching: if the user is in cache, return it; otherwise call the real repo and cache the result. Which pattern?

3A NestJS interceptor wraps the route handler to add response transformation and timing. Which pattern does it most resemble?

4You integrate a payment provider whose SDK returns XML. Your system uses JSON objects. You write a wrapper that parses XML to JSON and exposes your PaymentGateway interface. Which pattern?

5Express middleware that adds request ID, logging, and auth check before passing to the next handler. Each middleware wraps the next. Which pattern?

6You need to use an AWS S3 client but your storage interface expects upload(path, data) → url. S3's API uses putObject with buckets, keys, and ACLs. Which pattern?

7You add rate limiting to an existing API client by wrapping it. Before each call, check the rate limit. Same interface as the original client. Which pattern?

8Key test: if you remove the wrapper, does the system break because of interface mismatch, or because it loses a feature?