Skip to content
Back to blog
Design Patterns

Decorator Pattern: Extending Behavior Without Changing the Original

Updated 20 min read

The Decorator Pattern lets you extend an object's behavior without modifying its core implementation. Learn how to compose logging, retries, and caching in TypeScript, understand why decorator order matters, and avoid common mistakes involving error handling, idempotency, and excessive abstraction.

Table of Contents

Introduction

As software grows, existing components often need new capabilities.

A payment client may need logging. An API client may need retries. A repository may need caching. A service may need metrics or access control.

The straightforward approach is to add these responsibilities directly to the original implementation.

typescript
class PaymentClient {
  async charge(amount: number): Promise<void> {
    console.log(`Charging ${amount}`);

    // Validate the request.
    // Retry transient failures.
    // Call the payment provider.
    // Record metrics.
    // Handle errors.
  }
}

Initially, this seems reasonable. Everything is in one place, and the implementation is easy to follow.

Over time, however, the component accumulates responsibilities that are not part of its primary purpose. Changes to logging, retries, or monitoring can affect the same implementation, making it harder to test and maintain.

Inheritance offers one way to extend behavior, but it can become awkward when multiple optional capabilities need to be combined.

The Decorator Pattern offers another approach: wrap an existing object with another object that implements the same interface and adds behavior before or after delegating to the original.

Instead of modifying the payment client, we can compose it with separate logging, retry, or metrics decorators.

The result is a system where behavior can be extended without repeatedly changing the underlying implementation.

The Decorator Pattern separates additional responsibilities from the component's core behavior while preserving the interface that clients depend on.

1. The Problem: Components Accumulate Too Many Responsibilities

Consider an application that sends notifications through an external provider.

The initial implementation is simple:

typescript
interface NotificationSender {
  send(recipient: string, message: string): Promise<void>;
}

class EmailNotificationSender implements NotificationSender {
  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    // Call the email provider API.
  }
}

The sender has one responsibility: deliver a notification.

Now suppose the application needs additional capabilities:

  • Log delivery attempts and failures.
  • Retry transient provider errors.
  • Record metrics.
  • Enforce a rate limit.
  • Cache data used by a read-oriented dependency.

One option is to place all these concerns inside the original implementation.

typescript
class EmailNotificationSender implements NotificationSender {
  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    // Log the request.
    // Check rate limits.
    // Retry provider calls.
    // Record metrics.
    // Deliver the notification.
    // Handle failures.
  }
}

This may work initially, but the implementation now has multiple reasons to change.

A modification to retry behavior can affect delivery logic. Changes to logging can make the class harder to test. Another provider may need the same monitoring and retry capabilities, leading to duplicated code.

We could create specialized subclasses, but the number of combinations may grow:

text
EmailNotificationSender
├── LoggingEmailNotificationSender
├── RetryingEmailNotificationSender
├── LoggingRetryingEmailNotificationSender
└── LoggingRetryingRateLimitedEmailNotificationSender

Adding another independent capability creates more possible combinations.

The underlying issue is not that the sender needs more functionality. It is that unrelated responsibilities are being combined into one implementation or encoded into a growing inheritance hierarchy.

A better question is:

Can we add these capabilities without changing the sender or creating a separate subclass for every combination?

The Decorator Pattern answers that question through composition.

2. The Core Idea Behind the Decorator Pattern

The Decorator Pattern is a structural design pattern that adds responsibilities to an object by wrapping it with another object that implements the same interface.

The structure has three main elements:

  1. Component: The interface defining the behavior clients expect.
  2. Concrete component: The original implementation of that behavior.
  3. Decorator: A wrapper that implements the same interface, holds another component, and adds behavior around it.

The relationship looks like this:

text
Client
  |
  v
Logging Decorator
  |
  v
Retry Decorator
  |
  v
Concrete Component

The client interacts with the outermost decorator through the same interface it would use for the original component.

When the client invokes an operation, the decorators can perform additional work before delegating to the wrapped component. They can also inspect the result, handle errors, or perform cleanup afterward.

For example:

typescript
class LoggingSender implements NotificationSender {
  constructor(
    private readonly inner: NotificationSender,
  ) {}

  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    console.info(`Sending notification to ${recipient}`);

    await this.inner.send(recipient, message);

    console.info(`Notification sent to ${recipient}`);
  }
}

The decorator implements NotificationSender, just like the original sender.

That means another component can use either implementation without needing to know which one it received.

typescript
const original: NotificationSender =
  new EmailNotificationSender();

const decorated: NotificationSender =
  new LoggingSender(original);

Both values satisfy the same contract.

The decorator does not replace the original implementation. It extends it by controlling how calls reach that implementation.

Why must the interface remain the same?

Preserving the interface is what makes decorators composable.

If LoggingSender exposed a completely different API, callers would need special handling for decorated objects. That would undermine the purpose of the pattern.

By implementing the same interface, decorators can be added, removed, or reordered at the composition boundary without changing the client code.

This also makes it possible to test each decorator independently by supplying a fake implementation.

The essential rule is simple:

A decorator should add a responsibility without forcing its caller to learn a new interface.

3. Implementing Decorator in TypeScript

Let's build a more complete example using the notification sender.

Step 1: Define the component contract

typescript
interface NotificationSender {
  send(recipient: string, message: string): Promise<void>;
}

The interface describes what the application needs, not how a notification is delivered.

The implementation might use email, SMS, a third-party notification service, or a test double.

Step 2: Implement the concrete component

typescript
class EmailNotificationSender implements NotificationSender {
  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    // Call the email provider API.
    console.info(`Email sent to ${recipient}`);
  }
}

This implementation focuses on delivery.

It does not need to know how the application logs operations or decides whether a failed request should be retried.

Step 3: Add a logging decorator

typescript
interface Logger {
  info(message: string): void;
  error(message: string): void;
}

class LoggingNotificationSender implements NotificationSender {
  constructor(
    private readonly inner: NotificationSender,
    private readonly logger: Logger,
  ) {}

  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    this.logger.info(`Sending notification to ${recipient}`);

    try {
      await this.inner.send(recipient, message);
      this.logger.info(`Notification sent to ${recipient}`);
    } catch (error) {
      this.logger.error(`Notification failed for ${recipient}`);
      throw error;
    }
  }
}

The logging decorator records the operation and delegates delivery to the wrapped sender.

It also preserves the failure semantics by rethrowing the error.

This matters because a decorator should not silently turn a failed operation into an apparent success unless changing that behavior is explicitly part of its contract.

In production systems, logging should also avoid recording sensitive message contents or personal data unnecessarily.

Step 4: Add a retry decorator

Some provider failures are temporary. A network timeout or a rate-limit response may be recoverable, while an invalid recipient or rejected authorization request may not be.

We can isolate retry behavior in another decorator.

typescript
class RetryNotificationSender implements NotificationSender {
  constructor(
    private readonly inner: NotificationSender,
    private readonly maxAttempts: number,
    private readonly shouldRetry: (error: unknown) => boolean,
    private readonly delay: (attempt: number) => Promise<void>,
  ) {
    if (
      !Number.isInteger(maxAttempts) ||
      maxAttempts < 1
    ) {
      throw new Error(
        "maxAttempts must be a positive integer",
      );
    }
  }

  async send(
    recipient: string,
    message: string,
  ): Promise<void> {
    for (let attempt = 1; ; attempt++) {
      try {
        await this.inner.send(recipient, message);
        return;
      } catch (error) {
        const shouldStop =
          attempt >= this.maxAttempts ||
          !this.shouldRetry(error);

        if (shouldStop) {
          throw error;
        }

        await this.delay(attempt);
      }
    }
  }
}

The retry decorator delegates the decision about retryable errors and delays to injected functions.

For example, an application might provide exponential backoff:

typescript
const delayWithBackoff = async (
  attempt: number,
): Promise<void> => {
  const delayMs = Math.min(
    200 * 2 ** (attempt - 1),
    5_000,
  );

  await new Promise<void>((resolve) => {
    setTimeout(resolve, delayMs);
  });
};

This example demonstrates the structure rather than a complete production retry policy. A production implementation may also need jitter, cancellation, a total deadline, and provider-specific handling for Retry-After responses.

There is another important concern: retrying a side-effecting operation can cause duplicates.

If the provider processes a notification but the response is lost, the client may retry an operation that already succeeded. Use provider-supported idempotency keys or an appropriate delivery design when duplicate delivery would be harmful.

The decorator makes retry behavior reusable, but it does not make every operation safe to retry.

Step 5: Compose the decorators

The application can now assemble the desired behavior:

typescript
const emailSender: NotificationSender =
  new EmailNotificationSender();

const retryingSender: NotificationSender =
  new RetryNotificationSender(
    emailSender,
    3,
    isTransientProviderError,
    delayWithBackoff,
  );

const notificationSender: NotificationSender =
  new LoggingNotificationSender(
    retryingSender,
    logger,
  );

await notificationSender.send(
  "[email protected]",
  "Your report is ready.",
);

Here, isTransientProviderError and logger are application-provided implementations.

The resulting composition is:

text
LoggingNotificationSender
  └── RetryNotificationSender
        └── EmailNotificationSender

The client interacts only with NotificationSender.

It does not need to know how many decorators exist or which provider ultimately delivers the notification.

If we later need metrics or tracing, we can introduce additional decorators and compose them at the same boundary.

What have we achieved?

The core sender remains focused on delivery. Logging and retry behavior can be implemented and tested separately. The application can choose which capabilities to apply without modifying the sender itself.

This is the practical value of the pattern: independent responsibilities become composable building blocks.

4. Understanding Decorator Composition and Order

Decorators are composable, but their order is not necessarily interchangeable.

Consider these two arrangements:

typescript
const senderA: NotificationSender =
  new LoggingNotificationSender(
    new RetryNotificationSender(
      emailSender,
      3,
      isTransientProviderError,
      delayWithBackoff,
    ),
    logger,
  );
typescript
const senderB: NotificationSender =
  new RetryNotificationSender(
    new LoggingNotificationSender(
      emailSender,
      logger,
    ),
    3,
    isTransientProviderError,
    delayWithBackoff,
  );

In the first arrangement, logging wraps the entire retry operation. It typically records one overall operation, while the retry decorator handles individual attempts internally.

In the second arrangement, logging is inside the retry decorator. Each attempt passes through the logger, making attempt-level failures and successes visible.

CompositionTypical behaviorAppropriate when
Logging → Retry → ClientLogs the overall operationYou want a summary for each logical request
Retry → Logging → ClientLogs individual attemptsYou need detailed retry diagnostics
Cache → RepositoryChecks the cache before reading the repositoryYou want to avoid unnecessary reads
Authorization → Cache → RepositoryChecks authorization before returning cached dataCache access depends on the current caller
Retry → Rate Limit → ClientEach attempt passes through the rate limiterEvery outbound attempt must be rate-limited
Rate Limit → Retry → ClientThe retry sequence is wrapped by the limiterYou intend to limit logical operations rather than individual attempts

These examples describe common behavior, not universal guarantees. Each decorator's implementation determines exactly when it executes and what it counts.

For example, a rate limiter placed outside a retry decorator might acquire permission once for the whole logical operation. A limiter inside the retry decorator can acquire permission for every attempt.

The same distinction applies to metrics, tracing, transactions, caching, and authorization.

Before adding a decorator, ask:

  • Should this behavior run once per logical operation or once per attempt?
  • Should it execute before or after the wrapped operation?
  • Should it inspect the original result or a transformed result?
  • Which failures should pass through unchanged?
  • Does its position affect security, correctness, or resource usage?

Composition is powerful precisely because order can express meaningful policy.

5. Practical Use Cases: Logging, Retry, and Caching

The pattern is especially useful when a capability can be separated from the core behavior and applied consistently across multiple implementations.

Logging and observability

Logging, metrics, and tracing are common examples.

An API client should primarily send requests. A logging decorator can record operation details, while a metrics decorator can measure duration and success or failure counts.

This is useful when several clients need the same observability behavior.

However, observability code must be designed carefully. Logging should avoid sensitive payloads, metrics should avoid unbounded label cardinality, and instrumentation failures should not accidentally replace the original business error unless that is an explicit policy.

Retry and resilience

Retry decorators can centralize transient-failure handling for external clients.

They are useful when retry rules are consistent across operations and can be expressed without changing the underlying interface.

However, not every operation should be retried. A read request may be naturally repeatable, while a payment or notification operation may require idempotency protection.

Retry policies should also respect deadlines, cancellation, provider rate limits, and error classification.

Caching

Caching is another common application of the pattern.

Suppose an application depends on a read-only data source:

typescript
interface UserReader {
  getById(id: string): Promise<User | null>;
}

A caching decorator can implement UserReader, check a cache first, and delegate to the underlying reader on a cache miss.

typescript
class CachedUserReader implements UserReader {
  constructor(
    private readonly inner: UserReader,
    private readonly cache: {
      get(
        key: string,
      ): Promise<User | null | undefined>;

      set(
        key: string,
        value: User | null,
        ttlSeconds: number,
      ): Promise<void>;
    },
  ) {}

  async getById(id: string): Promise<User | null> {
    const key = `user:${id}`;
    const cached = await this.cache.get(key);

    if (cached !== undefined) {
      return cached;
    }

    const user = await this.inner.getById(id);

    await this.cache.set(key, user, 60);

    return user;
  }
}

This example assumes the cache distinguishes a miss (undefined) from a cached result of null. The latter allows negative caching when a user does not exist.

A production implementation must also consider invalidation, serialization, concurrent cache misses, and cache failures.

ConcernDesign question
Cache keyDoes the key include every input that affects the result?
AuthorizationCould two callers with different permissions receive the same cached result?
InvalidationHow does the system handle updates or deletions?
ExpirationHow stale can the result safely become?
Negative cachingShould missing records be cached, and for how long?
Cache failureShould a failed cache lookup fail the operation or fall back to the source?

For example, if results vary by tenant or permission, a key based only on the user ID may return data to the wrong caller.

A decorator provides a clean place to implement caching behavior, but it does not remove the need for a correct cache policy.

Comparing common use cases

Use caseWhat the decorator addsImportant trade-off
LoggingOperation details and failure recordsSensitive data and logging overhead
MetricsDuration and outcome measurementsInstrumentation overhead and metric cardinality
RetryRepeated attempts for eligible failuresDuplicate side effects and increased latency
CachingReuse of previously retrieved resultsStale data, invalidation, and isolation
Rate limitingControl over operation frequencyQueueing, rejection, and throughput constraints

Not every concern needs to be a decorator. HTTP-specific behavior may fit middleware better, and some security checks belong at an explicit application or domain boundary.

Choose the mechanism that makes the responsibility easiest to understand and enforce.

6. Decorator vs. Inheritance, Adapter, Proxy, and Strategy

Several design patterns can look similar because they use indirection, composition, or interchangeable implementations. Their primary intentions are different.

PatternPrimary intentionTypical example
DecoratorAdd responsibilities around an existing objectAdd logging to a payment client
AdapterMake incompatible interfaces work togetherWrap a third-party SDK behind an application interface
ProxyControl access to an objectLazy loading or access control
StrategyEncapsulate interchangeable algorithmsSelect a payment provider
InheritanceExtend or specialize a typeCreate a specialized notification sender
MiddlewareProcess operations through a pipelineHTTP authentication and request logging

Decorator vs. inheritance

Inheritance extends behavior through a class hierarchy. Decorator extends behavior through composition.

Suppose a notification sender can independently support logging, retries, metrics, and rate limiting.

With inheritance, we may need subclasses representing combinations of these capabilities. With decorators, we can assemble only the behaviors a particular application needs.

InheritanceDecorator
Behavior is encoded in subclassesBehavior is assembled through wrappers
Combinations may create many specialized classesCombinations can be composed at runtime
Useful for genuine subtype relationshipsUseful for optional, independent capabilities
Behavior is closely tied to the class hierarchyBehavior can be reused across compatible implementations

Inheritance is still appropriate when a genuine subtype relationship exists and the variation belongs in the type's design.

Decorator is more attractive when the system needs independently composable behavior.

Decorator vs. Adapter

An Adapter changes the interface presented to a client so an incompatible implementation can satisfy the client's expectations.

A Decorator preserves the interface and adds behavior around the implementation.

For example, wrapping a third-party payment SDK whose methods differ from the application's PaymentGateway contract is an Adapter use case.

Adding logging or retries around the resulting PaymentGateway is a Decorator use case.

The two patterns can be combined: an adapter can normalize an external API, and decorators can add observability or resilience around that normalized interface.

Decorator vs. Proxy

A Proxy controls access to an object. It may delay initialization, restrict access, or mediate operations.

A Decorator primarily adds responsibilities while preserving the component's interface.

The structures can be almost identical. In practice, the distinction is often about intent: lazy loading suggests Proxy, while adding metrics or retry behavior suggests Decorator.

Access control can be implemented using either structure, depending on whether the primary concern is controlling access or adding a reusable responsibility.

Decorator vs. Strategy

Strategy encapsulates an interchangeable algorithm or behavior. A client chooses which strategy to use.

Decorator wraps an existing component to add behavior around it.

For example, choosing between email and SMS delivery is a Strategy-like decision. Adding logging to whichever sender is selected is a Decorator-like decision.

The patterns can work together: an application can select a delivery strategy and then wrap it with logging and retry decorators.

Decorator vs. middleware

Decorator typically wraps an object that implements an interface. Middleware usually participates in a request-processing pipeline, such as an HTTP server's request and response lifecycle.

DecoratorMiddleware
Usually wraps an object or serviceUsually participates in a processing pipeline
Often applied to a particular dependencyOften applied to requests or framework execution
Common for client-level caching, logging, and retriesCommon for authentication, CORS, and request IDs
Can be composed during dependency constructionOften registered in a framework-defined order

These are conventions rather than strict boundaries. Middleware can use wrapping internally, and decorators can be used inside a middleware-based application.

If a concern applies to every HTTP request, middleware may be the natural choice. If it applies to a particular service dependency, a decorator may provide a clearer boundary.

7. Common Decorator Mistakes

Creating a decorator for every small operation

Not every additional line of behavior deserves a new class.

If the behavior is tiny, local, and unlikely to vary independently, a helper function may be clearer.

Use decorators when the added responsibility has a meaningful boundary or is reusable across implementations.

Changing the underlying contract

A decorator should preserve the behavior callers reasonably expect from the component, except for the explicitly intended enhancement.

A logging decorator should not silently swallow errors. A retry decorator should not turn a failed operation into apparent success. A caching decorator should document its freshness behavior.

If a wrapper changes timing, failure, consistency, or delivery semantics, those consequences should be deliberate.

Retrying every failure

Validation errors, authorization failures, and permanent provider rejections usually should not be retried.

Retries need explicit error classification, bounded attempts, sensible backoff, and an overall time budget.

For operations with side effects, consider idempotency keys or another mechanism that prevents duplicate processing.

Ignoring decorator order

Two decorators that work correctly in isolation can behave differently when composed in a different order.

Logging outside retry may record one logical operation; logging inside retry may record every attempt. Authorization and caching also require careful ordering when cached data depends on the current caller.

Make order explicit when it affects correctness, security, or observability.

Hiding too much behind composition

A deeply nested chain can become difficult to understand:

text
Tracing
  -> Metrics
    -> Authorization
      -> Rate Limiting
        -> Retry
          -> Logging
            -> Client

The system may be modular in code but opaque during debugging.

Keep the composition visible in one place, give decorators descriptive names, and document any ordering constraints.

Introducing abstraction without a real need

If a component has one implementation and no meaningful optional behavior, introducing an interface plus several decorators may create more complexity than value.

Design patterns should clarify decisions, not merely increase the number of classes.

8. When Should You Use Decorator?

Decorator is a good fit when:

  • You need to add optional behavior around an existing implementation.
  • The added behavior can be separated from the component's primary responsibility.
  • Multiple implementations should share the same additional capability.
  • Different environments need different combinations of behavior.
  • You want to test the added behavior independently.
  • Modifying the core component would create unnecessary coupling.

Avoid it when:

  • The behavior is simple and unlikely to evolve independently.
  • The wrapper changes the contract in surprising ways.
  • Too many layers make execution difficult to understand.
  • A framework already provides a clearer mechanism, such as HTTP middleware.
  • The requirement is actually to select a different algorithm or implementation, which may call for Strategy.
  • The system needs durable asynchronous delivery rather than in-process wrapping; a message queue or event-driven architecture may be more appropriate.

A practical rule is to introduce a decorator when it represents a coherent capability that can be added, removed, or tested independently.

If the wrapper exists only to forward a call without adding a meaningful responsibility, reconsider whether the abstraction is necessary.

Summary

The Decorator Pattern provides a way to extend an object's behavior without repeatedly modifying its core implementation.

By wrapping an object with another implementation of the same interface, the application can compose responsibilities such as logging, metrics, retries, and caching while keeping the original component focused.

The most important ideas are:

  • Same interface: Decorators remain compatible with the component they wrap.
  • Composition: Additional responsibilities can be combined without creating a subclass for every combination.
  • Explicit ordering: The position of a decorator can change behavior, observability, and security.
  • Independent testing: Each decorator can be tested using a fake or stub component.
  • Deliberate trade-offs: Retries, caching, and other wrappers introduce their own correctness and operational concerns.

Decorator is not a reason to wrap every class or move every cross-cutting concern into a new abstraction.

Use it when composition makes responsibilities clearer and more reusable. Prefer a simpler implementation when the extra layer does not provide enough value.

A good decorator adds a capability without making the original component responsible for knowing that the capability exists.

  • Design Patterns
  • Decorator Pattern
  • OOP
  • Programing
  • Software Architecture
  • Object Composition
  • Middleware vs Decorator
  • Proxy Pattern
  • Retry Pattern
  • Caching Decorator
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.