Decorator adds behavior to one object by wrapping it in another object with the same interface. The wrapper does a little work before or after passing each call on to the object it wraps, and because it looks exactly like what it wraps, wrappers can be stacked: Logging(Compression(Encryption(file))). Features are combined at runtime, in any order and any number, instead of with one subclass per combination or a pile of flags in one class.
Think of it like
Wrapping a parcel
You put a gift in a box, the box in bubble wrap, and the bubble wrap in a padded envelope. Each layer adds one thing (shape, cushioning, an address label) and still presents the same kind of thing to the outside: a package that can be carried and handed over. The courier never needs to know how many layers there are. Unwrapping goes in the reverse order, outermost first, and if you wrap in the wrong order (the label inside the bubble wrap) the result is different, even though every layer did its job.
The problem
An app stores text through a DataSource with write(data) and read(). Some data should be compressed, some encrypted, some both. The quick design is one class with a boolean flag per feature and the feature code inside it. This is the Before version in the visualizer above.
class FileSource implements DataSource {
private data = "";
constructor(
private compress: boolean,
private encrypt: boolean,
) {}
write(data: string) {
if (this.compress) data = zip(data);
if (this.encrypt) data = lock(data);
this.data = data;
}
read() {
let d = this.data;
if (this.encrypt) d = unlock(d); // undo in the reverse order
if (this.compress) d = unzip(d);
return d;
}
}
const file = new FileSource(true, true); // which true is which?- Every feature edits the same class. Adding logging means a third flag, a new field and a branch in both
writeandread, inside a class that already holds compression and encryption. - Every call site changes too.
new FileSource(true, true)becomesnew FileSource(true, true, true), including the places that do not want logging at all. - The order is frozen. Compress-then-encrypt is written into the class twice (forward in
write, backward inread). A caller that needs another order, or the same feature twice, cannot have it. - Every object carries every feature. A plain file still holds the encryption code and checks its flag on every call. With
nflags the class has2ⁿcombinations to keep correct. - Subclasses are worse. One subclass per combination (
CompressedFile,EncryptedFile,CompressedEncryptedFile...) is the class explosion from Composition vs Inheritance: three features already need up to seven subclasses, before caring about order.
The pattern
Intent: attach additional responsibilities to an object dynamically; decorators provide a flexible alternative to subclassing for extending functionality (Gang of Four, who also call it Wrapper). In practice: put each feature in its own class that implements the same interface as the object it wraps, holds a reference to it, and adds its work around the forwarded call.
- Component (
DataSource) - The interface clients use. Both the real object and every decorator implement it, which is what makes them interchangeable and stackable.
- Concrete component (
FileSource) - The core object that does the real work, here storing and returning text. It knows nothing about the decorators.
- Decorator (
Decorator) - An abstract base class that implements the component interface and holds the wrapped component (
protected wrapped: DataSource). By default each method just forwards, so a concrete decorator overrides only what it changes. - Concrete decorators (
Compression,Encryption, laterLogging) - One class per feature. Each adds behavior before forwarding (compress, then pass the result on) or after the inner call returns (pass on, then decompress the result).
- Client
- Builds the stack at runtime, from the inside out:
new Compression(new Encryption(file)). After that it only sees aDataSource.
Two arrows in the class diagram carry the whole idea. Decorator implements DataSource, so a decorator can go anywhere a data source can. Decorator also holds a DataSource (the aggregation labeled wraps), so what it wraps can be the real file or another decorator. Being one and having one at the same time is what lets wrappers nest to any depth.
What the visualizer shows
- Class diagram:
DataSourceon top,FileSourceand the abstractDecoratorbelow it, and the concrete decorators underDecorator. Every call from one layer to the next lights the wraps aggregation and the violetDataSourceinterface, because each decorator calls the next one only through that interface. - Objects at runtime: two towers of objects. On the left,
src : Compressionpoints toenc : Encryptionthroughwrapped, which points tofile. Watch the argument change as the call goes down:"aaaabb", then"4a2b", then"4b4e"infile.data. - Sequence of calls: the strongest moment. A
read()goes three calls deep (src,enc,file), so three activation bars nest inside each other, and then three returns come back out, each with a different value:"4b4e","4a2b","aaaabb".
Press Play, or step with the arrow buttons: the visualizer really runs the classes in the code panel and explains each step in the caption under the stage. The Before / With Decorator toggle switches to the flags version, where one FileSource object does everything and there is never a second call. Add logging applies the change request to whichever version is shown; touched classes get a badge (new class or edited), and the Change request panel beside the code compares the two versions. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create the core object
With With Decorator selected, the client runs
new FileSource(). The objectfileonly stores text; itsdatastarts as"". - 2
Build the stack from the inside out
new Encryption(file)createsencwithwrapped = file, thennew Compression(enc)createssrcwithwrapped = enc. Both constructors only store the reference. - 3
The call travels inward
src.write("aaaabb")runsCompression.write, which compresses first and callsenc.write("4a2b").Encryption.writeshifts that and callsfile.write("4b4e"). The file stores"4b4e": 4 characters. - 4
Control unwinds
Three returns come back,
filetoenc,enctosrc,srcto the client.writereturns nothing, so no layer has anything to add on the way out. - 5
The result travels outward
src.read()goes three calls deep without doing any work, because each layer needs the inner result first. Thenfilereturns"4b4e",Encryptionturns it into"4a2b", andCompressionturns that into"aaaabb". - 6
Stack the same decorators the other way round
The client builds
bad = new Encryption(new Compression(file2))and writes the same"aaaabb". Encryption now runs first and produces"abcdfg", which has no runs left to compress. - 7
Order matters
file2stores"1a1b1c1d1f1g": 12 characters instead of 4, from the same two classes and the same input. It still reads back correctly; it is just three times larger. - 8
Add logging (change request)
With Add logging applied, the client wraps a new
Loggingaround the stack.Loggingrecords"write 6"before forwarding and"read 6"after the inner read returns. No existing class changed.
Before and after
One class with flags
- Every feature is an
ifinwriteand another inread - One fixed order, written into the class twice
- A new feature edits the class and every constructor call
new FileSource(true, false, true)hides its meaning- Fewer objects and calls at runtime: one object does it all
With Decorator
- One small class per feature, each testable on its own
- The client picks features and their order when it builds the stack
- A new feature is a new class; nothing existing is opened
new Compression(new Encryption(file))reads like the data flow- More small objects, and one extra call per layer
| Change request: add logging | Before (flags) | With Decorator |
|---|---|---|
| Existing classes edited | 1 (FileSource) | 0 |
| New classes | 0 | 1 (Logging) |
| Lines changed in existing classes | 10 | 0 |
The panel counts classes only. The client code changed in both versions too, but differently: with flags, every new FileSource(...) needed a third argument, including the encryption-only file that does not log; with Decorator, only the one stack that wants logging gained a new Logging(...) around it.
Variations
Transparent and semi-transparent decorators
A transparent decorator adds behavior only through the existing interface, so clients cannot tell it is there (Compression changes what write does, not what methods exist). A semi-transparent decorator also adds new methods. Java's BufferedReader wraps any Reader and adds readLine(); Python's functools.lru_cache wraps a function and adds cache_info() and cache_clear(). The catch: those extra methods are only reachable through a reference typed as the decorator, and they disappear as soon as another decorator wraps it.
Order sensitivity
Decorators do not commute in general. The visualizer shows the classic case: encrypted output looks random, so compression after encryption finds nothing to remove; compress first. (Real systems add a caveat: compressing secret data together with attacker-controlled data before encrypting can leak information through the output length, which is how the CRIME and BREACH attacks on HTTPS worked.) Other order effects are everyday ones: a cache outside a logger logs only misses, a logger outside a cache logs every call; a retry decorator outside an auth decorator runs it again on every attempt (so each attempt can get a fresh token), while inside it every attempt re-sends the one token attached before the first try.
Identity: the wrapper is not the original
decorated === originalis false. Code that tracks objects by reference (aSet, a map key, a listener list) sees two different objects.instanceofchecks see the wrapper's class.Collections.unmodifiableList(arrayList) instanceof ArrayListis false in Java, and a check forFileSourcefails onsrc. Code that needs such checks is fighting the pattern.- Equality has to be decided on purpose. Java's unmodifiable and synchronized list wrappers forward
equalsandhashCodeto the wrapped list; a decorator that inherits the default identityequalsdoes not. - Python function decorators copy the wrapped function's name and docstring when they use
functools.wraps, and keep the original in__wrapped__. Without it, every decorated function reports the wrapper's name.
Functional decorators
When the component interface is a single function, a decorator can be a higher-order function: it takes a function and returns a new function with the same signature that adds work around the call. memoized(logged(square)) is the Decorator pattern without classes. The second implementation below builds exactly that and shows that order still matters.
Python's @decorator syntax is related but not the same thing. Writing @lru_cache above def f is shorthand for f = lru_cache(f): it runs once, when the function is defined, and rebinds the name. The callable after @ may return a wrapper (that is the Decorator pattern in function form, as with lru_cache), but it may also register the function and return it unchanged (Flask's @app.route) or return a different kind of object entirely (@property returns a descriptor). The syntax is a definition-time hook; the pattern is about wrapping objects with the same interface. JavaScript and TypeScript decorators (@logged on a class or method) come from a TC39 proposal that reached stage 3; TypeScript 5.0 implements it, while older code uses TypeScript's experimentalDecorators flag, which follows an earlier draft. Like Python's, they run when the class is defined and can replace a method with a wrapped one. They are a convenient way to apply the same wrapping to every instance of a class, not a way to decorate one object at runtime.
Middleware chains apply the idea to request handlers. A middleware takes the next handler and returns a handler that does something before and after calling it, and a server stacks many of them around the application (a common Go idiom is literally func(next http.Handler) http.Handler). Many middleware systems also let a layer answer the request itself without calling the next one, an authentication check that rejects the request, for example. That ability to stop the chain is the defining trait of Chain of Responsibility, so real middleware usually sits between the two patterns.
In real code
| Where | Component | Decorators |
|---|---|---|
java.io byte streams | InputStream, with FileInputStream as a concrete component | FilterInputStream is the decorator base (it holds the wrapped stream in a field named in); BufferedInputStream, DataInputStream and GZIPInputStream extend it, as in new BufferedInputStream(new FileInputStream("data.bin")) |
java.io character streams | Reader | BufferedReader wraps any Reader and adds readLine() (semi-transparent). InputStreamReader, which turns a byte stream into a Reader, is an Adapter, not a decorator: it changes the interface |
java.util.Collections | List, Set, Map... | unmodifiableList(list) returns a wrapper whose mutators throw UnsupportedOperationException; synchronizedList(list) returns one that synchronizes every call. Both forward the rest to the original list |
Python functools | A function | @functools.lru_cache returns a wrapper that caches results by argument and adds cache_info() and cache_clear(); functools.wraps helps hand-written decorators keep the wrapped function's name |
| HTTP clients and servers | A request handler or a send function | Interceptors and middleware add logging, authentication headers, retries, compression or metrics around the real call |
java.io is the textbook example and also its best-known drawback: reading lines from a compressed file takes several nested constructors (a BufferedReader around an InputStreamReader around a GZIPInputStream around a FileInputStream). Lots of small objects that are only useful together is the price of Decorator's flexibility, and libraries often add convenience factories on top (Files.newBufferedReader(path)) for the common stacks.
When to use it, and when not to
Reach for Decorator when
- Optional features wrap the same operation and must combine freely
- Different objects, or the same object at different times, need different combinations
- Subclassing per combination would explode, or the class is final or third party
- The features are cross-cutting: logging, caching, retries, metrics, access checks
- You want to add a feature without editing tested code (the open/closed principle in SOLID Principles)
Skip it when
- There is one fixed combination; just write it
- The feature needs the object's private state, not just its interface
- Callers depend on object identity or concrete types
- The interface is large, so every decorator must forward dozens of methods
- Stack order would be easy to get wrong and nobody owns building it
Decorator vs similar patterns
| Pattern | Interface | Holds | Purpose |
|---|---|---|---|
| Decorator | Same as the wrapped object | One component | Add responsibilities; wrappers are stacked by the client in any combination |
| Adapter | Different: converts one interface into another | One adaptee | Make an existing class fit; it adds no new behavior on purpose |
| Proxy | Same as the subject | One subject, often created or looked up by the proxy itself | Control access: lazy creation, remote calls, permissions, caching. Same structure as Decorator, different intent, and usually not stacked by the client |
| Composite | Same as its children | Many children | Treat a tree of objects like one object. The Gang of Four describe a decorator as a degenerate composite with exactly one component |
| Chain of Responsibility | Same handler interface | The next handler | Each handler may stop the chain and answer itself; a decorator always forwards |
| Strategy | The context's own | One strategy | Swap the algorithm inside an object. In the Gang of Four's words, a decorator changes the skin of an object and a strategy changes its guts |
Implementation
The visualizer's scenario as a complete program: a DataSource interface, FileSource as the core object, an abstract Decorator that holds the wrapped source, and Compression, Encryption and Logging decorators. The demo writes and reads through a three-layer stack, then shows that stacking compression and encryption the other way round stores three times as much. The codecs are deliberately toy algorithms.
import re
from abc import ABC, abstractmethod
from itertools import groupby
class DataSource(ABC):
@abstractmethod
def write(self, data: str) -> None: ...
@abstractmethod
def read(self) -> str: ...
class FileSource(DataSource):
"""Concrete component: the core object, no optional features."""
def __init__(self) -> None:
self._data = ""
def write(self, data: str) -> None:
self._data = data
def read(self) -> str:
return self._data
class Decorator(DataSource):
"""Base decorator: holds the wrapped source, forwards by default."""
def __init__(self, wrapped: DataSource) -> None:
self._wrapped = wrapped
def write(self, data: str) -> None:
self._wrapped.write(data)
def read(self) -> str:
return self._wrapped.read()
# Toy codecs: run-length "compression" and a position-shift "cipher".
def zip_text(s: str) -> str:
return "".join(f"{len(list(run))}{ch}" for ch, run in groupby(s))
def unzip_text(s: str) -> str:
return re.sub(r"(\d+)(\D)", lambda m: m.group(2) * int(m.group(1)), s)
def shift(s: str, k: int) -> str:
return "".join(chr(ord(c) + k * i) for i, c in enumerate(s))
class Compression(Decorator):
def write(self, data: str) -> None:
self._wrapped.write(zip_text(data)) # before forwarding
def read(self) -> str:
return unzip_text(self._wrapped.read()) # after the inner call
class Encryption(Decorator):
def write(self, data: str) -> None:
self._wrapped.write(shift(data, 1))
def read(self) -> str:
return shift(self._wrapped.read(), -1)
class Logging(Decorator):
"""The change request: one new class, nothing else edited."""
def __init__(self, wrapped: DataSource) -> None:
super().__init__(wrapped)
self.log: list[str] = []
def write(self, data: str) -> None:
self.log.append(f"write {len(data)}")
self._wrapped.write(data)
def read(self) -> str:
d = self._wrapped.read()
self.log.append(f"read {len(d)}")
return d
if __name__ == "__main__":
file = FileSource()
src = Logging(Compression(Encryption(file)))
src.write("aaaabb")
print(file.read()) # 4b4e (what is stored)
print(src.read()) # aaaabb
print(src.log) # ['write 6', 'read 6']
# Same decorators, other order: encryption destroys the runs.
file2 = FileSource()
bad = Encryption(Compression(file2))
bad.write("aaaabb")
print(file2.read()) # 1a1b1c1d1f1g (12 characters, not 4)
print(bad.read()) # aaaabb (still correct, just larger)Key takeaways
- Decorator wraps an object in another object with the same interface that adds work before or after forwarding each call, so features stack at runtime in any combination.
- A decorator both is a component (implements the interface) and has a component (the
wrappedfield); that pair of relations is what makes nesting possible. - Calls travel inward through the layers and results come back outward; work done before forwarding affects the inner layers, work done after affects the result.
- Order matters: compression after encryption saves nothing, and a cache outside a logger hides repeated calls from it.
- In the visualizer's "Add logging" request, Decorator adds 1 class and edits none, while the flags version edits
FileSource(10 lines) and every constructor call. - Same structure, different intent: Adapter changes the interface, Proxy controls access, Strategy swaps the inside, Decorator adds to the outside.
Common pitfalls
- Stacking decorators in the wrong order. Decide which layer must see the raw data (logging, compression) and build common stacks in one place instead of at every call site.
- Relying on identity or concrete types:
wrapped !== original,instanceof FileSourcefails on a decorator, and maps keyed by the original miss the wrapper. - Forgetting to forward a method. With a large interface, a decorator that does not override every method (or extend a base that forwards them) silently loses behavior or breaks the contract.
- Losing semi-transparent extras: methods a decorator adds (
readLine(),cache_info()) are unreachable once another decorator wraps it. - Using a decorator when the feature needs the wrapped object's internals. A decorator only sees the public interface; if it starts casting to reach private state, the feature belongs in the class.
Interview tips
- Draw the two relations that define the pattern: the decorator implements the component interface and holds a reference to a component. Then write
new Logging(new Compression(new Encryption(file)))and walk a call in and back out. - Mention order sensitivity with a concrete example (compress before encrypt, cache outside the logger); interviewers often ask "does the order matter?"
- Name real examples:
java.iostreams (new BufferedInputStream(new FileInputStream(...))),Collections.unmodifiableList, Python'sfunctools.lru_cache, HTTP middleware. - Be ready to separate it from Proxy (same structure, controls access), Adapter (changes the interface) and Chain of Responsibility (handlers may stop the chain).
Real-world applications
- I/O streams: buffering, compression, encryption, checksums and typed reads stacked around a file or socket stream.
- Collection views: read-only, synchronized or checked wrappers around an existing collection.
- HTTP clients and servers: logging, authentication, retries, timeouts and metrics as interceptors or middleware around the real call.
- Caching and memoization: a cache layer in front of a slow service or function with the same interface.
- UI components: borders, scroll bars and shadows added around a widget (the Gang of Four's original example).
- Pricing and text: add-ons that each add cost and description to an order, or formatting layers around a text renderer.
Test yourself
What makes it possible to wrap a decorator inside another decorator?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.