Skip to Content
Mengty Learns
Design

Decorator Pattern

Layer cross-cutting behaviors like logging, caching, and retries around an object without changing its interface or subclassing.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

1. Intent

TL;DR

Attach additional responsibilities to an object dynamically by wrapping it inside one or more Decorator objects that implement the exact same interface as the core component.

2. Problem

Suppose you have an HttpClient interface with a single request(url) method. Over time, different services need combinations of retries on 503s, in-memory response caching, and structured request logging.

If you add those combinations via inheritance (RetryingHttpClient, CachedHttpClient, LoggedCachedRetryingHttpClient), every new feature doubles the number of subclasses. Even worse, you cannot toggle caching or retries per environment at runtime without building yet another subclass.

Combining optional behaviors via inheritance multiplies subclasses rapidly.

3. Solution

Create wrapper classes (LoggingDecorator, CacheDecorator, RetryDecorator) that all implement the same HttpClient interface and take another HttpClient in their constructor.

Each decorator runs its own pre- and post-processing around this.inner.request(req). Because every wrapper looks like an HttpClient from the outside, you can stack them in any order at startup without changing caller code.

4. Real-world analogy

5. Flow: watch it work

Decorator Pattern: Logging → Cache → Retry → HTTP

Overview of Decorator Pattern: Logging → Cache → Retry → HTTP. 8 steps.
Overview8 steps in this flow

Press Start or tap any step dot to trace the path.

▸All steps (8)

6. Structure

Every Decorator implements HttpClient and wraps another HttpClient instance.

7. Code

interface HttpRequest {
  method: 'GET' | 'POST';
  url: string;
}

interface HttpResponse {
  status: number;
  body: string;
}

// Component interface
interface HttpClient {
  request(req: HttpRequest): Promise<HttpResponse>;
}

// Concrete Component
class FetchHttpClient implements HttpClient {
  async request(req: HttpRequest): Promise<HttpResponse> {
    return { status: 200, body: `ok:${req.method}:${req.url}` };
  }
}

// Decorator 1: Retry transient failures
class RetryHttpClient implements HttpClient {
  constructor(
    private readonly inner: HttpClient,
    private readonly maxAttempts = 3,
  ) {}

  async request(req: HttpRequest): Promise<HttpResponse> {
    let lastError: unknown;
    for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
      try {
        const res = await this.inner.request(req);
        if (res.status < 500 || attempt === this.maxAttempts) return res;
      } catch (err) {
        lastError = err;
        if (attempt === this.maxAttempts) throw lastError;
      }
    }
    throw lastError;
  }
}

// Decorator 2: In-memory GET cache
class CachedHttpClient implements HttpClient {
  private readonly cache = new Map<string, HttpResponse>();

  constructor(private readonly inner: HttpClient) {}

  async request(req: HttpRequest): Promise<HttpResponse> {
    if (req.method === 'GET') {
      const hit = this.cache.get(req.url);
      if (hit) return hit;
    }
    const res = await this.inner.request(req);
    if (req.method === 'GET' && res.status === 200) {
      this.cache.set(req.url, res);
    }
    return res;
  }
}

// Decorator 3: Structured logging
class LoggingHttpClient implements HttpClient {
  constructor(private readonly inner: HttpClient) {}

  async request(req: HttpRequest): Promise<HttpResponse> {
    const start = Date.now();
    const res = await this.inner.request(req);
    console.log(`[http] ${req.method} ${req.url} -> ${res.status} (${Date.now() - start}ms)`);
    return res;
  }
}

// Compose stack: Logging -> Cache -> Retry -> FetchHttpClient
const client: HttpClient = new LoggingHttpClient(
  new CachedHttpClient(
    new RetryHttpClient(new FetchHttpClient(), 3),
  ),
);

await client.request({ method: 'GET', url: 'https://api.example.com/health' });

8. When to use / when to avoid

When to use
  • You need to compose optional, orthogonal behaviors (logging, caching, retries, auth headers) in different combinations at runtime.
  • You cannot or should not subclass the core component (e.g. third-party classes or final-like modules).
  • Each cross-cutting concern should stay small and testable in isolation.
When to avoid
  • Wrapper order is implicit and error-prone without clear documentation (e.g. caching *outside* auth leaks tenant responses).
  • You need to inspect or remove a specific middle layer dynamically after construction.
  • A simple middleware array or pipeline function (`middlewares.reduceRight(...)`) is cleaner than nested `new A(new B(new C()))`.

When NOT to use it

Overengineering occurs when you wrap a single concrete class in three decorators that are always used together in the exact same order. If nobody ever composes them differently, a single well-factored class (or a small helper function) is far easier to read than four constructor-chained wrappers.

Real-world example in this stack

In Next.js (next.config.mjs) and Fumadocs (lib/source.ts), configuration and loader plugins wrap base config objects with additional capabilities (MDX compilation, search indexing) while preserving the underlying config contract.

9. How to implement

Define the Component interface

Keep the contract (HttpClient.request) narrow so every wrapper is easy to implement.

Implement the Concrete Component

Write the core FetchHttpClient with zero logging, caching, or retry logic.

Create Decorators wrapping HttpClient

Each decorator implements HttpClient, accepts inner: HttpClient, and delegates to this.inner.request(req).

Document and wire the stack order

Assemble the chain at your composition root (Logging -> Cache -> Retry -> Fetch) and verify order-dependent interactions.

10. Pros / Cons

Pros
  • Compose behaviors dynamically without combinatorial subclassing.
  • Single Responsibility Principle: each wrapper handles one cross-cutting concern.
  • Open/Closed Principle: add a new wrapper (e.g. circuit breaker) without touching existing wrappers.
Cons
  • Deeply nested `new A(new B(new C()))` construction is noisy to read.
  • Order-dependent bugs (e.g. Retry outside Cache vs Cache outside Retry) can be subtle.
  • Hard to remove a specific inner decorator once the stack is built.

11. Relations

Decorator vs Adapter

Decorator keeps the same interface and stacks recursively; Adapter changes an incompatible interface to match what callers expect.

Decorator vs Proxy

Both share the component interface and wrap another object, but Proxy controls access/lifecycle (lazy init, auth) whereas Decorator layers new behavior.

Decorator vs Chain of Responsibility

Both pass calls along a chain, but Chain handlers can short-circuit independently while Decorators enrich the same operation.

12. Check yourself

Check Yourself

1. In a stack Logging(Cached(Retry(Fetch))), what happens on a cache hit for a GET request?

2. How does Decorator differ from Adapter?

Sources