7
← Back to Pattern Arsenal
structural

Decorator

must know

Stage 1: Problem

The Problem

You are building an HTTP client library. The basic client makes requests:

typescript
1class HttpClient {
2 async request(url: string, options: RequestOptions): Promise<Response> {
3 return fetch(url, options);
4 }
5}

Now you need to add behaviors:

  1. Logging — log every request and response for debugging.
  2. Retry — retry failed requests up to 3 times with exponential backoff.
  3. Caching — cache GET responses for 5 minutes.
  4. Authentication — automatically attach Bearer tokens to requests.
  5. Rate limiting — throttle outbound requests to stay under API limits.

And the killer requirement: these behaviors must be composable. One service needs logging + retry. Another needs auth + caching. A third needs all five. The combination varies per use case.

How do you add optional, combinable behaviors to an object without an explosion of subclasses?


1 / 10 — Problem