Decorator
Also known as: Wrapper
Add behavior to an object dynamically by wrapping it in objects that share its interface.
- 7 animated steps
- 6 languages
- Structural patterns
The problem
You want to write data with compression, encryption, both, or neither. With inheritance you get CompressedEncryptedFileSource and every other possible combination.
The solution
Create "wrappers" that implement the same interface as the base object, add their own processing, then delegate to the wrapped object. They can be stacked freely.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- Base object: all it knows is how to write raw data.
- It gets wrapped in a compression decorator…
- …then in an encryption decorator. Same interface at every layer.
- The client sees a plain DataSource.
- Layer 1: encrypts, then delegates.
- Layer 2: compresses, then delegates.
- The base object writes to disk, unaware of the layers added around it.
An analogy
Dressing in layers: t-shirt, sweater, then raincoat. Each layer adds a property, and you can remove or combine them at will.
When to use it
- Adding responsibilities without modifying the class
- HTTP middleware, logging, caching, retry, metrics
- Many possible combinations of features
Pros and cons
Pros
- Combinations at runtime, with no subclass explosion
- Single Responsibility: one layer = one role
- Open/Closed
Cons
- Stacking order matters and can be subtle
- Debugging a long stack of wrappers
Implementations
The same example, written idiomatically in each language.
Decorator in Python
class DataSource:
def write(self, data: str) -> str:
return f"disk <- {data}"
class Decorator(DataSource):
def __init__(self, wrapped: DataSource):
self.wrapped = wrapped
class Encryption(Decorator):
def write(self, data):
return self.wrapped.write(data[::-1]) # demo "encryption"
class Compression(Decorator):
def write(self, data):
return self.wrapped.write(f"zip({data})")
src = Encryption(Compression(DataSource()))
print(src.write("secret")) # disk <- zip(terces)
# Python also has function decorators: @functools.cache, @retry…
Decorator in TypeScript
interface DataSource { write(data: string): string; }
class FileDataSource implements DataSource {
write(data: string) { return "disk <- " + data; }
}
abstract class Decorator implements DataSource {
constructor(protected wrapped: DataSource) {}
abstract write(data: string): string;
}
class Encryption extends Decorator {
write(d: string) { return this.wrapped.write(btoa(d)); }
}
class Compression extends Decorator {
write(d: string) { return this.wrapped.write("zip(" + d + ")"); }
}
const src = new Encryption(new Compression(new FileDataSource()));
src.write("secret"); // disk <- zip(c2VjcmV0)
Decorator in Java
interface DataSource { String write(String data); }
class FileDataSource implements DataSource {
public String write(String d) { return "disk <- " + d; }
}
abstract class Decorator implements DataSource {
protected final DataSource wrapped;
Decorator(DataSource wrapped) { this.wrapped = wrapped; }
}
class Encryption extends Decorator {
Encryption(DataSource w) { super(w); }
public String write(String d) {
return wrapped.write(Base64.getEncoder().encodeToString(d.getBytes()));
}
}
class Compression extends Decorator {
Compression(DataSource w) { super(w); }
public String write(String d) { return wrapped.write("zip(" + d + ")"); }
}
// Real-world example from the JDK:
// new BufferedReader(new InputStreamReader(new FileInputStream(file)))
Decorator in C#
interface IDataSource { string Write(string data); }
class FileDataSource : IDataSource
{
public string Write(string d) => $"disk <- {d}";
}
abstract class Decorator(IDataSource wrapped) : IDataSource
{
protected IDataSource Wrapped { get; } = wrapped;
public abstract string Write(string data);
}
class Encryption(IDataSource w) : Decorator(w)
{
public override string Write(string d) =>
Wrapped.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(d)));
}
class Compression(IDataSource w) : Decorator(w)
{
public override string Write(string d) => Wrapped.Write($"zip({d})");
}
IDataSource src = new Encryption(new Compression(new FileDataSource()));
Decorator in PHP
interface DataSource { public function write(string $data): string; }
class FileDataSource implements DataSource
{
public function write(string $data): string { return "disk <- $data"; }
}
abstract class Decorator implements DataSource
{
public function __construct(protected DataSource $wrapped) {}
}
class Encryption extends Decorator
{
public function write(string $data): string
{
return $this->wrapped->write(base64_encode($data));
}
}
class Compression extends Decorator
{
public function write(string $data): string
{
return $this->wrapped->write("zip($data)");
}
}
echo (new Encryption(new Compression(new FileDataSource())))->write('secret');
// Laravel middleware relies on the same wrapping principle
Decorator in Go
type DataSource interface{ Write(data string) string }
type FileDataSource struct{}
func (FileDataSource) Write(d string) string { return "disk <- " + d }
type Encryption struct{ Wrapped DataSource }
func (e Encryption) Write(d string) string {
return e.Wrapped.Write(base64.StdEncoding.EncodeToString([]byte(d)))
}
type Compression struct{ Wrapped DataSource }
func (c Compression) Write(d string) string {
return c.Wrapped.Write("zip(" + d + ")")
}
src := Encryption{Compression{FileDataSource{}}}
fmt.Println(src.Write("secret"))
// Very common Go idiom: func(next http.Handler) http.Handler
Frequently asked questions
What is the Decorator design pattern?
Add behavior to an object dynamically by wrapping it in objects that share its interface. Create "wrappers" that implement the same interface as the base object, add their own processing, then delegate to the wrapped object. They can be stacked freely.
When should you use the Decorator pattern?
Adding responsibilities without modifying the class; HTTP middleware, logging, caching, retry, metrics; Many possible combinations of features.
What are the pros and cons of the Decorator pattern?
Pros: Combinations at runtime, with no subclass explosion; Single Responsibility: one layer = one role; Open/Closed. Cons: Stacking order matters and can be subtle; Debugging a long stack of wrappers.