Pattern 06/22 · Structural
Decorator
Wrap an object in another object with exactly the same interface to add responsibilities (log, retry, cache, validate) around the call — the client does not know, and does not need to know, that it is holding the wrapped version.
01 — It starts with code that is breaking
Problem
Your StripeGateway.pay() is 12 lines long and works fine. Then the first requirement lands: "log every transaction". You add a console.log at the start and end of the function. Second requirement: "on a 5xx, retry 3 times with backoff". You wrap the HTTP call in a for loop. Third: "never send twice for the same idempotency key". You add a Map that remembers results. Fourth: circuit breaker. Fifth: a pay_duration_ms metric.
Now pay() is 140 lines long. It no longer contains payment logic — it contains payment logic plus five things that have nothing to do with payments, and you cannot turn any of them off without editing it. The test "is the pay flow correct" now has to go through the logger and whatever is sitting in the cache, or you mock three things.
Then product wants different combinations depending on the call site: the refund API does not retry, the payment API retries 3 times, the offline job retries 10 times with sampled logging. Your function mutates into pay(amount, opts: { retry?: boolean, log?: boolean, cache?: boolean, dryRun?: boolean }), with if (opts.retry && !opts.dryRun) inside. Four flags is 16 behaviors, you are sure about exactly 2 of them, and the fifth nested if is on its way.
Someone suggests inheritance: LoggedStripe, then RetryLoggedStripe extends LoggedStripe, then CachedRetryLoggedStripe. You have just pushed the combination matrix into class names, and worse: the retry logic lives inside a Stripe subclass, so the day the SMS gateway needs that exact retry, you either copy 40 lines or rework the whole inheritance tree.
This is not specific to payments. In Vue/React it looks like: a component wrapped in withAuth, then wrapped again in withTrack, then in withI18n, each written by a different person, none aware the other three exist; or four useFetchWithRetry files copy-pasted from each other because nobody bothered to pull "retry" out into its own thing. What breaks as the project grows is very concrete: cross-cutting behavior gets smeared all over business code, so you cannot turn it off, cannot test it in isolation, and one endpoint's policy leaks into another.
02 — The idea, before touching code
Solution
Decorator: write an object with the same interface as the thing it wraps, take that object at construction time (constructor(private inner: PaymentGateway)), and add its own work around the call to inner — before, after, or by repeating the call. StripeGateway does not change a single line.
Because the wrapper is also a PaymentGateway, it can wrap other wrappers: new WithLog(new WithRetry(new WithCache(gateway))). The client keeps the interface and cannot tell how many layers are inside. The entire "policy" (where to log, how many retries, which layer sits outside) becomes configuration code in one place, wiping out the if (opts.retry) tree.
In JS/TS the most common shape is not a class but a function that takes a function and returns a function of the same shape: withRetry(send) gives you a new send. React calls it a HOC (React.memo, withTranslation), Express calls it a plugin, Nitro calls it defineCachedEventHandler, Zustand calls it middleware. One pattern, four names. A warning up front to avoid confusion: TypeScript's @decorator syntax is not the Decorator pattern — it is a class-definition-time hook, with an entirely different intent and run time (Step 6).
03 — Doing it for real, one code fragment per step
Step by step
Call the interface, not the class
This is where things stand: pay() is still clean, but the three XXX lines below are three debts about to come due — every time product asks for more logging, retries, caching, metrics, we have to crack open this very business function again.
Prerequisite: the client must call through an interface (or a function type), not new StripeGateway() all over the place. Without that there is nothing to wrap — a wrapper has nowhere to stand.
export interface PaymentGateway {
pay(amount: number): string
}
/** ConcreteComponent: the ONLY place that touches the vendor SDK. */
export class StripeGateway implements PaymentGateway {
pay(amount: number): string {
// XXX: clients import this class directly -> nowhere left to insert a wrapper
// XXX: "add logging for this endpoint" = edit this exact business function
// XXX: add log + retry + cache + metric and these 12 lines balloon to 140
return 'stripe: OK ' + amount + ' VND'
}
}
// checkout.ts, refund.ts, cron-retry.ts — each one does it differently:
// const gateway = new StripeGateway() // no retry, no log
// const gateway = new StripeGateway(true) // the "with retry" version someone added laterPaymentGateway, not StripeGateway.The first decorator: logging, with zero changes to the component
A wrapper does only three things: take the inner object, call it, add something around the call. It does not know whether the inside is Stripe or Portal, and does not need to.
import type { PaymentGateway } from './component'
import { StripeGateway } from './component'
/** ConcreteDecorator: same interface, one added responsibility. */
export class WithLog implements PaymentGateway {
constructor(private inner: PaymentGateway, private tag: string) {}
pay(amount: number): string {
const out = this.inner.pay(amount)
console.log('[' + this.tag + '] ' + out)
return out
}
}
const gateway: PaymentGateway = new WithLog(new StripeGateway(), 'audit')
gateway.pay(150_000)
gateway.pay(20_000)[audit] stripe: OK 150000 VND [audit] stripe: OK 20000 VND
WithLog and everything still runs as before.Stacking: the order of the layers is the policy
Since every layer is a PaymentGateway, you can stack them in any order — and the order changes behavior. WithLog(WithRetry(gateway)) logs once for the final result; WithRetry(WithLog(gateway)) logs every attempt because the log sits inside the retry loop.
Want the metric to include retry time? Put WithMetric outside WithRetry. Want logs meant for the customer only (no 503s leaking)? Put WithLog outermost. Want internal debug logs for every attempt? Put it innermost. This is exactly the kind of decision an if (opts.log) tree can never express clearly.
const forCustomers: PaymentGateway =
new WithLog(new WithRetry(new WithMetric(new StripeGateway()), 3), 'audit')
const forDebugging: PaymentGateway =
new WithRetry(new WithLog(new StripeGateway(), 'attempt'), 3)
// The client of both: exactly the same.
const result = forCustomers.pay(150_000)The real JS version: a decorator is a function that takes a function
If your component is already a function (call an API, send mail, read the DB), the most natural decorator is a higher-order function of the same shape — no class, no interface file:
type Pay = (amount: number) => string
const withLog = (inner: Pay, tag: string): Pay =>
(amount) => {
const out = inner(amount)
console.log('[' + tag + '] ' + out)
return out
}
const withRetry = (inner: Pay, max: number): Pay =>
(amount) => {
let out = ''
for (let i = 0; i < max; i++) {
out = inner(amount)
if (!out.includes('503')) break
}
return out
}
const pay: Pay = withLog(withRetry(rawStripePay, 3), 'audit')instanceof still means something; function decorators when everything is a single call. Do not force the GoF shape onto JS code.Decorators around I/O: timeout, retry, cache — quite literally
Three decorators around a fetch-like function, written the way you would actually write them in server/api/. Note that each layer owns its own policy and does not pass that policy down to other layers.
type Fetcher = (url: string) => string
/** Timeout: wrap with an AbortController, add a named error. */
const withTimeout = (inner: Fetcher, ms: number): Fetcher =>
(url) => {
const ac = new AbortController()
const timer = setTimeout(() => ac.abort(), ms)
try {
return inner(url) // signal: ac.abort.signal when using the real fetch
}
finally {
clearTimeout(timer)
}
}
/** Cache: turn a function into a memoized function, key = url. */
const withCache = (inner: Fetcher, ttlMs: number): Fetcher => {
const memo = new Map<string, { at: number, value: string }>()
return (url) => {
const hit = memo.get(url)
if (hit && hit.at + ttlMs > Date.now()) return hit.value
const value = inner(url)
memo.set(url, { at: Date.now(), value })
return value
}
}
// with the real fetch: inner needs to take a signal -> use type Fetcher = (url, signal) => Promise<Response>withTimeout, withRetry, withCache written once, used for every endpoint. This is the part of the pattern that pays for itself.TypeScript's `@decorator` is a different thing, do not confuse them
TypeScript 5 supports standard ECMAScript decorators (stage 3) — the @ syntax placed on class members. It is a class-definition-time hook: it receives the original method + context and returns a replacement method. It does not create a new object, does not layer around an instance, and the client cannot choose "with this decorator, without that one" at runtime.
// @ syntax: transforms a method when the class is DEFINED (metadata hook).
function timed<This, Args extends unknown[], R>(
method: (this: This, ...args: Args) => R,
ctx: ClassMethodDecoratorContext,
) {
return function (this: This, ...args: Args): R {
const t0 = performance.now()
const out = method.apply(this, args)
console.log(String(ctx.name) + ' took ' + Math.round(performance.now() - t0) + 'ms')
return out
}
}
class Gateway {
@timed
pay(amount: number) { return 'OK ' + amount + ' VND' }
}@decorator = syntax that patches a class member. You can use the @ syntax to write a decorator, but the two concepts are not the same thing.Three things decorators break: instanceof, `this`, side effects
gateway instanceof StripeGateway is false — the wrapper is not Stripe. If some code relies on instanceof for special treatment, your decorator has silently broken it. To keep it open, expose readonly inner or an unwrap() function; to lock it down, ban instanceof against interface types.
Pulling a method off the object loses this (const pay = gateway.pay; pay(100)), and with function decorators this is the wrapper, not the component. You must use arrows or bind. And every retry layer re-runs side effects: if the API is not idempotent, your retry is a double charge — which is why WithRetry may only sit in front of APIs that take an idempotency key.
const gateway: PaymentGateway = new WithLog(new WithRetry(new StripeGateway(), 3), 'audit')
// 1) identity: the wrapper is not the component
console.log(gateway instanceof StripeGateway) // false
console.log(gateway instanceof WithLog) // true — but nobody wants to rely on that
// 2) this: pulling a method off the object loses this
const pay = gateway.pay
// pay(150_000) // -> this === undefined, crash
const payBound = gateway.pay.bind(gateway) // or declare the method as an arrow
console.log(payBound(150_000))
// 3) call count: retry multiplies side effects
class WithIdempotentRetry implements PaymentGateway {
constructor(readonly inner: PaymentGateway, private max: number) {}
pay(a: number) {
// the API MUST accept an idempotency key, otherwise 3 attempts = 3 charges
return this.inner.pay(a)
}
}instanceof and idempotency before stacking layers.Vue/Nuxt: composables and middleware are decorators too — and when to stop
In the Vue world, the "take a thing of some type, return the same type with added behavior" shape is everywhere: React.memo(C) / withTranslation(C) are component decorators; defineAsyncComponent, withDefaults are component/composable decorators; Nitro has defineCachedEventHandler(handler) wrapping an event handler with a cache; Zustand has persist, devtools wrapping a state creator. In Nuxt, writing withAuth(handler) that returns a new middleware is a decorator.
Where to stop: 2–3 layers is normal; 6 layers means you have written your own middleware framework and it needs docs. Add a decorator when the behavior is reusable in ≥ 2 places and turning it on/off is a real decision. Used exactly once, nobody ever turns it off? Write it straight into the function — Decorator is not an obligation.
// server/api/rates.get.ts — Nitro wraps the handler with a cache, the handler is unchanged.
export default defineCachedEventHandler(async (event) => {
return await $fetch('https://api.example.com/rates')
}, { maxAge: 60 })
// A hand-written decorator for Nuxt route middleware:
export const withAuth = (handler: (to: any) => any) =>
(to: any) => {
if (!useCookie('session').value) return navigateTo('/login')
return handler(to)
}04 — Who talks to whom
Structure
- ComponentThe shared interface: `pay(amount): string`. This is all the client knows.
- ConcreteComponent`StripeGateway` — the thing that actually does the work, knows nothing about logging/retry.
- DecoratorThe role of holding an `inner: Component` reference. In TS you usually do not need a parent class for this role.
- ConcreteDecoratorOne responsibility: `WithLog`, `WithRetry`, `WithCache`. Calls inner before/after/repeatedly.
- ClientReceives a fully assembled `PaymentGateway`; does not know (and need not know) how many layers there are.
Client ─── gateway.pay(150000) (only knows PaymentGateway)
│
▼
┌────────────────────────────────────────┐
│ ConcreteDecorator: WithLog │ adds a log AFTER the call
│ - inner: PaymentGateway │
└───────────────────┬────────────────────┘
▼ (every box is a PaymentGateway)
┌────────────────────────────────────────┐
│ ConcreteDecorator: WithRetry │ REPEATS the call, up to 3
│ - inner: PaymentGateway │
└───────────────────┬────────────────────┘
▼
┌────────────────────────────────────────┐
│ ConcreteComponent: StripeGateway │ the only place doing HTTP
└────────────────────────────────────────┘
Swap the top 2 layers = change the number of log lines. Drop 1 layer =
1 line changed. Add a layer = 1 new file. StripeGateway and Client: 0.05 — Edit freely, run it right here
Try it: the same two decorators, two orders, two behaviors
interface PaymentGateway {
pay(amount: number): string
}
/** Component: the thing that actually calls the payment gateway (deliberately 503s the first 2 times). */
class Stripe implements PaymentGateway {
private tries = 0
pay(amount: number): string {
this.tries++
if (this.tries < 3) return 'stripe: 503 (try ' + this.tries + ')'
return 'stripe: OK ' + amount + ' VND'
}
}
/** Decorator: same interface, adds the retry responsibility. */
class WithRetry implements PaymentGateway {
constructor(private inner: PaymentGateway, private max: number) {}
pay(amount: number): string {
let out = ''
for (let i = 0; i < this.max; i++) {
out = this.inner.pay(amount)
if (!out.includes('503')) break
}
return out
}
}
/** Decorator: logging. Also a PaymentGateway, so it slots into any layer. */
class WithLog implements PaymentGateway {
constructor(private inner: PaymentGateway, private tag: string) {}
pay(amount: number): string {
const out = this.inner.pay(amount)
console.log('[' + this.tag + '] ' + out)
return out
}
}
const a: PaymentGateway = new WithLog(new WithRetry(new Stripe(), 3), 'client')
const b: PaymentGateway = new WithRetry(new WithLog(new Stripe(), 'try'), 3)
console.log('A) WithLog on the outside: the customer sees just 1 log line')
a.pay(150_000)
console.log('B) WithLog on the inside: every attempt gets logged')
b.pay(150_000)A) WithLog on the outside: the customer sees just 1 log line [client] stripe: OK 150000 VND B) WithLog on the inside: every attempt gets logged [try] stripe: 503 (try 1) [try] stripe: 503 (try 2) [try] stripe: OK 150000 VND
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- There is a cross-cutting responsibility that applies in many places: logging, metrics, timeout, retry, cache, auth, rate limiting, encryption.
- You need to freely combine responsibilities per call site (refund: no retry, payment: retry 3, job: retry 10) — an
if/optstree cannot express it. - You are not allowed to modify the original code: a vendor SDK, a library, another team's module — but you need to add timeout/cache/validation around it.
- You want to test the core logic without I/O, then switch on layers one by one when you need to verify real behavior.
- Behavior must be toggleable at runtime by env, tenant, or feature flag, without touching business code.
- Watch for the opposite case: one responsibility, one call site, never turned off — do not wrap it, write it inline.
Don't use it when
- Over-engineering. A single use + no combinations to choose from = the decorator is one file of indirection and one extra jump-to-definition. The pattern is worth it when you have ≥ 2 decorators or ≥ 2 call sites sharing a policy.
- Layer order is your new bug. A cache inside retry will cache the error responses too; a metric inside retry will not count retry time; auth inside the cache will serve one user's data to the next user. Draw the stack on paper when you add the third layer.
- More layers make debugging longer: a stack trace thick with 6 wrapper frames, an exception "reinterpreted" at every layer. Each decorator must preserve the original error (do not
catch (e) { throw new Error("API call failed") }and throw away all the original info) and log with its own layer's tag. - A decorator is not transparent to
instanceof, tothiswhen a method is pulled off, or to call count. Retry multiplies side effects: if the API is not idempotent, your retry is a double charge. - Decorator is not TypeScript's
@decorator, nor is it Java-style AOP. When you say "decorator" on your team, be clear whether you mean the runtime object or the@syntax — this misunderstanding produces very long meetings.
07 — You have met it already, just not by name
In real code
p-retry, p-timeout, p-memoize, p-limit
This whole family of sindresorhus packages is exactly function-style decorators: pTimeout(promise, { milliseconds }) returns a promise wrapped with timeout behavior, pMemoize(fn) returns a function of the same shape with a cache, pLimit(3) wraps an async function to cap concurrent runs. You stack pLimit(withRetry(...)) in order — exactly the stacking story from Step 3.
Nitro defineCachedEventHandler and wrapper middleware in Nuxt
defineCachedEventHandler(handler, opts) takes an event handler, returns an event handler, and adds cache + lock + stale-while-revalidate behind it — your handler does not change. Same shape: defineNuxtRouteMiddleware lets you write withAuth(handler) returning a new middleware. h3/nitro is full of "take a handler, return a handler" functions.
React HOCs and Vue composables
React.memo(C), connect(mapState)(C), withTranslation(C), React.forwardRef(C) all take a component and return a component — component decorators, stackable, and the order matters (memo inside or outside connect gives different perf). Vue takes a different route but the same shape: a composable takes a ref/state and returns a ref/state with added behavior (a hand-written useFetch + retry + debounce).
Zustand middleware and Express compression()
create(persist(creator, { name })) in Zustand: persist takes a state creator and returns a state creator that also reads/writes localStorage — a pure decorator. On the server side, Express's compression() wraps res.write/res.end to gzip the response stream: a decorator applied to methods of a live object, a close sibling of Proxy.
08 — Try it yourself
Exercise
You have `type Sender = (phone: string, text: string) => string`. Write `withRateLimit(inner: Sender, perMinute: number): Sender` and `withAudit(inner: Sender): Sender`, then compose two cases: (a) the audit must record **the final result** after rate limiting, (b) the audit must record **every rejection**. Question: which stack for each case?
Hints, open them one at a time:
- Each decorator must return exactly the
Sendershape, otherwise they cannot wrap each other. withRateLimitneeds state (counting calls within a 1-minute window) — that state lives in the closure; make sure every call towithRateLimitgets its own counter.- The second question is just about order: an outermost audit sees the final result; an inner audit (closer to the sender) sees each rejection.
The two cases differ only in order. (a) withAudit(withRateLimit(send, 5)): the limiter runs first and returns LIMITED ... when exceeded; the outer audit records exactly one line for the final result (or for the reason it was blocked). (b) withRateLimit(withAudit(send), 5): the limiter decides first, but then the audit records nothing for blocked calls; to record rejections too, put the audit outermost as in (a) and have the limiter return a result containing LIMITED — the audit will log both kinds verbatim. Lesson: "who sees what" is decided entirely by stack order.
type Sender = (phone: string, text: string) => string
const send = (phone: string, text: string): string => 'SENT ' + phone + ' (' + text.length + ' chars)'
function withRateLimit(inner: Sender, perMinute: number): Sender {
const hits: number[] = []
return (phone, text) => {
const now = 1_000 // replace with Date.now() in real code
while (hits.length && now - hits[0] > 60_000) hits.shift()
if (hits.length >= perMinute) return 'LIMITED ' + phone
hits.push(now)
return inner(phone, text)
}
}
const withAudit = (inner: Sender): Sender =>
(phone, text) => {
const out = inner(phone, text)
console.log('[audit] ' + out)
return out
}
const sms = withAudit(withRateLimit(send, 2))
console.log('--- customer: log only the final result ---')
sms('0912', 'a')
sms('0912', 'bb')
sms('0912', 'ccc')09 — Read them in pairs to see the essence
Related patterns
- ProxySame shape (an object in the middle, holding a reference), different intent: Proxy **controls access** (lazy, permissions, remote, copy-on-write), Decorator **adds business responsibilities**. Many Proxies are also decorators and vice versa — read this pair to tell them apart by purpose, not by diagram.
- AdapterAdapter **changes** the interface to make it fit (`pay()` → `send()`), Decorator **keeps** the interface and adds behavior. If your decorator declares a different interface from what it wraps, it is an Adapter in disguise.
- Chain of ResponsibilityMiddleware in Express/Nuxt looks like Decorator but is Chain of Responsibility when each layer has the right to **refuse** to pass things on. With Decorator, every layer must call the inner layer to get the job done.
- StrategyStrategy **replaces** how something is done (pick one of many); Decorator **adds** around the existing way and stacks up. `new WithRetry(gateway)` + `new WithLog(gateway)` = both; `gateway = registry[driver]` = Strategy.