Decorator pattern

On this page 7

The decorator pattern is a structural design pattern that adds responsibilities to an object at runtime by wrapping it in another object that implements the same interface and forwards calls to it. In programming and software architecture, it offers a flexible alternative to subclassing: instead of creating a new class for every combination of features, developers compose small wrappers that each add one concern, such as logging, caching, compression or access checks.

The pattern was cataloged by the Gang of Four in 1994 under the alternative name wrapper. It remains one of the most widely used structural patterns because it supports the open/closed principle: existing code stays untouched while new behavior is layered around it.

How the decorator pattern wraps an object

A decorator works by holding a reference to a component and exposing the same operations as that component. When a client calls a method, the decorator may run its own logic before or after the call, then delegates to the wrapped object. Because the client sees only the shared interface, it cannot tell whether it talks to the original object or to a chain of decorators.

The classic structure has four participants. Each role has a narrow job, which keeps every wrapper small and independently testable.

ParticipantRoleTypical example
ComponentInterface shared by real objects and wrappersDataSource with read and write
Concrete componentThe original object that does the core workFileDataSource
Base decoratorStores the wrapped component and forwards callsDataSourceDecorator
Concrete decoratorAdds one specific behavior around the callEncryptionDecorator, CompressionDecorator
Participants in the classic decorator structure

Decorators can be stacked in any order. A file source might be wrapped first by compression and then by encryption, so data is compressed before it is encrypted on write and decrypted before it is decompressed on read. The order of wrapping matters, because each layer sees the output of the layer beneath it.

Why composition beats subclassing here

The main motivation for the decorator pattern is avoiding a class explosion. With inheritance, three optional features such as buffering, encryption and compression would need up to seven subclasses to cover every combination, and a fourth feature would double that number. With decorators, the same three features need only three small classes that combine freely at runtime.

Composition also changes when behavior is decided. Inheritance fixes behavior at compile time, while decorators let configuration, user settings or feature flags decide which wrappers to apply when the program runs.

AspectSubclassingDecorator pattern
Binding timeCompile timeRuntime
Classes for n optional featuresUp to 2^n – 1n wrappers
Adding behavior to one instanceNot possibleWrap that instance only
Removing behaviorRequires another classOmit the wrapper
Access to internalsFull access to protected membersPublic interface only
Subclassing compared with decoration

Several structural patterns also wrap objects, so the decorator is easy to confuse with its neighbors. The decisive difference is intent: a decorator keeps the interface and adds behavior, while other wrappers change the interface, control access or simplify a subsystem.

PatternInterface exposedMain intent
Decorator patternSame as the wrapped objectAdd responsibilities dynamically
Adapter patternDifferent interfaceMake incompatible interfaces work together
Proxy patternSame as the wrapped objectControl access, lazy loading or remoting
Facade patternNew simplified interfaceHide a complex subsystem
Strategy patternSeparate algorithm interfaceSwap the internal algorithm
How the decorator differs from similar wrappers

The line between a proxy and a decorator is the subtlest. Both share the interface, but a proxy usually manages the lifecycle or access of its subject and often creates it itself, whereas a decorator receives an existing object and is meant to be stacked with other decorators. A strategy changes the object from the inside, while a decorator changes it from the outside.

Where the decorator pattern appears in practice

The pattern is common in I/O libraries, web middleware and cross-cutting concerns. Java streams are the textbook case: a BufferedInputStream wraps a FileInputStream, and a GZIPInputStream can wrap both. HTTP middleware pipelines in many frameworks follow the same idea, with each layer handling authentication, logging or rate limiting before passing the request on.

  • Caching decorators around a repository return stored results and call the real repository only on a miss.
  • Retry and circuit-breaker decorators around a network client add resilience without changing the client.
  • Metrics decorators record latency and error counts for any service that shares an interface.
  • Authorization decorators check permissions before forwarding a command to the business logic.

With dependency injection, decorators are usually registered in the container so that consumers receive the fully wrapped object automatically. Note that Python function decorators using the @ syntax are a language feature inspired by the same idea, but they wrap functions rather than objects that share a declared interface.

Limitations and common mistakes

Decorators trade class count for object count and indirection. Deep chains make stack traces longer, debugging harder and object identity checks unreliable, because the outermost wrapper is not the same object as the inner component. The following table lists typical problems and their fixes.

SymptomCauseFix
Wrong results after reorderingOrder-dependent wrappersDocument and centralize chain assembly
Equality or type checks failClient compares concrete typesProgram only against the interface
Huge boilerplate per decoratorWide interfaces with many methodsUse a base decorator or split the interface
Behavior silently skippedWrapper forgets to delegate one methodTest every forwarded operation
Hard-to-read stack tracesVery deep chainsLimit layers and name wrappers clearly
Typical decorator problems and remedies

A decorator should stay transparent to the client and add one concern only. When a wrapper starts to change the meaning of results or requires callers to know it exists, a different pattern, or a plain explicit call, is usually the cleaner design choice.

The short version

Think of a plain cup of coffee. You can add milk, then sugar, then a shot of caramel, and it is still a cup of coffee that you drink the same way. Each addition wraps the previous drink and adds something new.

The decorator pattern does the same with software objects. Instead of building a separate class for every possible mix of features, a program wraps one object in thin layers, and each layer adds a single extra behavior. The key point is that the outside stays the same, so the rest of the program never has to change.

Where it makes a difference

A development team runs an online store whose product service calls a slow pricing database. Response times reach about 400 milliseconds per request at peak load, and managers also want latency metrics and automatic retries after brief network failures.

Instead of editing the pricing client, the team writes three decorators that implement the same PriceProvider interface: a retry decorator that repeats failed calls up to three times, a caching decorator that keeps prices for 60 seconds, and a metrics decorator on the outside that measures every call. The dependency injection container assembles the chain at startup.

Average response time drops to under 50 milliseconds for cached prices, transient failures no longer reach customers, and the original client code remains unchanged and fully tested. When the team later disables caching for a flash sale, it simply removes one wrapper from the configuration.