Decorator Pattern
Add behavior through objects that share a contract, and see why wrapping order changes the result.
· Last updated: 2026-11-05 · 13 min read
Overview
A report starts out as plain body text, then one screen asks for a header title, a second screen asks for line numbers, and a third wants both. Minting a subclass for every combination (TitledReport, NumberedReport, TitledNumberedReport) explodes as options grow; breaking each enhancement into its own wrapper object and stacking them in order stays flat and composable.
The innermost object builds the core body, while each outer wrapper adds just its own layer. That is the Decorator pattern: wrappers implement the exact same IReport interface as the core object they hold, so callers invoke Render() without caring how many layers sit underneath.
UML
In the UML diagram, TextReport produces the raw text, while TitleReport and NumberedReport both implement IReport and hold another IReport reference named inner. Each wrapper delegates the core work to inner.Render() and transforms the returned string, no abstract Decorator base class required.
The object diagram traces one specific stack: TitleReport(NumberedReport(TextReport)). Calls enter from the left, reach TextReport on the right, and pick up line numbers first and the title second on the way back out.
History
In 1994, the Gang of Four (Gamma, Helm, Johnson, and Vlissides) cataloged Decorator as a structural pattern in Design Patterns.1
Java 1.0 shipped a textbook example in java.io.FilterInputStream: it extends InputStream, holds another InputStream inside, and forwards basic reads to that inner stream so subclasses can layer buffering, hashing, or data transformations on top, showing that the pattern is about runtime object composition rather than any language's @decorator syntax.2
Why use it?
Inheritance forces you to name every combination upfront as a distinct class. Decorators keep each feature in its own small class and wire them together at construction time, letting the exact same TextReport instance plug into any chain.
Sharing an interface means honoring behavioral expectations too, not just method signatures: if a Render() wrapper secretly fires off a network request or throws exceptions the caller never signed up for, the abstraction leaks. Cross-cutting wrappers like logging or caching should be explicit at the assembly site.
Whereas Strategy swaps out the core algorithm inside an object, a Decorator wraps around the object and augments what comes in or goes out. And if all you ever need is a single fixed string tweak, a plain function beats a wrapper class every time.
Example
using System;
using System.Linq;
IReport plain = new TextReport("Revenue: 100\nCost: 40");
IReport first = new TitleReport(new NumberedReport(plain), "October");
IReport second = new NumberedReport(new TitleReport(plain, "October"));
Console.WriteLine(first.Render());
Console.WriteLine("---");
Console.WriteLine(second.Render());
// The body and wrappers share one contract so wrappers can wrap other wrappers.
public interface IReport
{
string Render();
}
public sealed class TextReport : IReport
{
private readonly string text;
public TextReport(string text) => this.text = text;
public string Render() => text;
}
// Reuse the inner result and add only this wrapper’s behavior.
public sealed class TitleReport : IReport
{
private readonly IReport inner;
private readonly string title;
public TitleReport(IReport inner, string title)
{
this.inner = inner;
this.title = title;
}
public string Render() => title + "\n" + inner.Render();
}
public sealed class NumberedReport : IReport
{
private readonly IReport inner;
public NumberedReport(IReport inner) => this.inner = inner;
public string Render() => string.Join("\n", inner.Render().Split('\n')
.Select((line, index) => $"{index + 1}. {line}"));
}October
1. Revenue: 100
2. Cost: 40
---
1. October
2. Revenue: 100
3. Cost: 40In the first chain, line numbers wrap the body before October is prepended on the outside, so the title stays unnumbered; flip the wrapping order in the second chain and October becomes line 1. Callers invoke Render() identically either way: the outer wrapper always gets the final word.
Both chains refer to the same plain object. These wrappers create new strings without modifying the text held by TextReport. However deep the stack, the source object stays one.
An extended example
Logging and caching order
Now stack two operational wrappers: a cache that replays a stored result on subsequent calls, and a logger that records each invocation. Both implement the same interface, yet whichever wrapper sits on the outside determines what actually gets counted.
Here the cache stores only ReportResult.Success and passes ReportResult.Failure straight through, while the logger records a fixed call marker and SampleReport deliberately fails on its first invocation so we can watch how each ordering handles an initial failure.
using System;
using System.Collections.Generic;
var firstSource = new SampleReport();
var firstLog = new List<string>();
IReport cacheOutside = new CachedReport(new LoggedReport(firstSource, firstLog));
_ = cacheOutside.Render();
_ = cacheOutside.Render();
Console.WriteLine($"Cache outside: source={firstSource.Calls}, logs={firstLog.Count}");
var secondSource = new SampleReport();
var secondLog = new List<string>();
IReport logOutside = new LoggedReport(new CachedReport(secondSource), secondLog);
_ = logOutside.Render();
_ = logOutside.Render();
Console.WriteLine($"Log outside: source={secondSource.Calls}, logs={secondLog.Count}");
var failingSource = new SampleReport(failFirst: true);
IReport recoverable = new CachedReport(failingSource);
Console.WriteLine($"First failed: {recoverable.Render() is ReportResult.Failure}");
Console.WriteLine($"Second succeeded: {recoverable.Render() is ReportResult.Success}");
_ = recoverable.Render();
Console.WriteLine($"Source calls after three requests: {failingSource.Calls}");
public enum ReportError { Unavailable }
public abstract record ReportResult
{
private ReportResult() { }
public sealed record Success(string Text) : ReportResult;
public sealed record Failure(ReportError Code) : ReportResult;
}
// The body and wrappers share one contract so wrappers can wrap other wrappers.
public interface IReport
{
ReportResult Render();
}
public sealed class SampleReport : IReport
{
private readonly bool failFirst;
public int Calls { get; private set; }
public SampleReport(bool failFirst = false) => this.failFirst = failFirst;
public ReportResult Render()
{
Calls++;
if (failFirst && Calls == 1)
return new ReportResult.Failure(ReportError.Unavailable);
return new ReportResult.Success("Revenue: 100");
}
}
public sealed class LoggedReport : IReport
{
private readonly IReport inner;
private readonly List<string> log;
public LoggedReport(IReport inner, List<string> log)
{
this.inner = inner;
this.log = log;
}
public ReportResult Render()
{
log.Add("render requested");
return inner.Render();
}
}
public sealed class CachedReport : IReport
{
private readonly IReport inner;
private ReportResult.Success? cached;
public CachedReport(IReport inner) => this.inner = inner;
public ReportResult Render()
{
if (cached is not null)
return cached;
ReportResult result = inner.Render();
if (result is ReportResult.Success success)
cached = success;
return result;
}
}Cache outside: source=1, logs=1
Log outside: source=1, logs=2
First failed: True
Second succeeded: True
Source calls after three requests: 2Put the cache on the outside and the second call short-circuits before ever touching the inner logger, leaving a single log entry; put the logger on the outside and every caller request is recorded while the inner cache still builds the report only once. Decide whether you want to count total incoming requests or cache misses, then order the wrappers accordingly.
A failed first result is not cached. The second request invokes the source and succeeds; the third uses that success. These are three separate caller requests, not an automatic retry within the first. One rule drives the sequence: failures are not cached.
Reviewing the composition
What if someone places an audit logger or a per-request authorization check inside a cache wrapper? Every cache hit answers immediately from memory and skips the inner layers completely, silencing the audit trail and handing the first caller's authorized report to subsequent callers without checking their permissions!
This toy cache also assumes immutable single-threaded data; real caches need user-scoped keys, TTLs, and invalidation rules, just as stream decorators (BufferedInputStream, GZipStream) need a clear rule for which layer owns closing the underlying handle.
TypeScript example
Same contract, any depth. Because body text, titles, and line numbers live in separate classes that all implement IReport, you can stack as many layers as you like without changing a single line of caller code.
// The body and wrappers share one contract so wrappers can wrap other wrappers.
interface IReport { render(): string; }
class TextReport implements IReport {
constructor(private readonly text: string) {}
render(): string { return this.text; }
}
// Reuse the inner result and add only this wrapper’s behavior.
class TitleReport implements IReport {
constructor(private readonly inner: IReport, private readonly title: string) {}
render(): string { return this.title + "\n" + this.inner.render(); }
}
class NumberedReport implements IReport {
constructor(private readonly inner: IReport) {}
render(): string {
return this.inner.render().split("\n").map((line, index) => (index + 1) + ". " + line).join("\n");
}
}
const plain = new TextReport("Revenue: 100\nCost: 40");
console.log(new TitleReport(new NumberedReport(plain), "October").render());
console.log("---");
console.log(new NumberedReport(new TitleReport(plain, "October")).render());October
1. Revenue: 100
2. Cost: 40
---
1. October
2. Revenue: 100
3. Cost: 40Note that this is the GoF object-wrapping pattern rather than TypeScript's @decorator syntax: numbering before titling still produces a different string from titling before numbering.
Wrapping the same contract with Decorator<T>
Component<T> and Decorator<T> both return T from Operation(). A decorator calls its inner component and then processes the result, allowing layers to be composed while preserving the caller-facing result type.
Wrap a component returning 3 with + 1 and * 2, and the two Decorator<int> layers evaluate to either 8 or 7 depending on which wrapper sits on the outside, proving that generic type parameters preserve the shared contract without erasing wrapping order.
C#
using System;
IComponent<int> component = new Component<int>(() => 3);
var multiplyAfterAdd = new Decorator<int>(new Decorator<int>(component, x => x + 1), x => x * 2);
var addAfterMultiply = new Decorator<int>(new Decorator<int>(component, x => x * 2), x => x + 1);
Console.WriteLine(multiplyAfterAdd.Operation());
Console.WriteLine(addAfterMultiply.Operation());
// TYPES
interface IComponent<T> { T Operation(); }
sealed class Component<T> : IComponent<T>
{
private readonly Func<T> operation;
public Component(Func<T> operation) { this.operation = operation; }
public T Operation() => operation();
}
sealed class Decorator<T> : IComponent<T>
{
private readonly IComponent<T> inner;
private readonly Func<T, T> decorate;
public Decorator(IComponent<T> inner, Func<T, T> decorate)
{ this.inner = inner; this.decorate = decorate; }
// Decorate the inner result while keeping the same T contract.
public T Operation() => decorate(inner.Operation());
}8
7TypeScript
interface Component<T> { operation(): T; }
class ValueComponent<T> implements Component<T> {
constructor(private readonly produce: () => T) {}
operation(): T { return this.produce(); }
}
class Decorator<T> implements Component<T> {
constructor(private readonly inner: Component<T>, private readonly decorate: (value: T) => T) {}
// The inner and outer objects expose the same calling contract.
operation(): T { return this.decorate(this.inner.operation()); }
}
const component: Component<number> = new ValueComponent(() => 3);
const multiplyAfterAdd = new Decorator(new Decorator(component, x => x + 1), x => x * 2);
const addAfterMultiply = new Decorator(new Decorator(component, x => x * 2), x => x + 1);
console.log(multiplyAfterAdd.operation());
console.log(addAfterMultiply.operation());8
7This small variant processes a T and returns another T. Converting an int result into a string changes the calling contract and needs a design distinct from this same-contract decorator. The pattern wraps only processing that keeps the same result type.
The official references describe the type-parameter syntax and library contracts.3
Related reading
Footnotes
- Gamma, Helm, Johnson and Vlissides. Design Patterns (1994), Decorator. Publisher record. ↩
- Oracle. FilterInputStream, Since 1.0. An input-stream wrapper that delegates to the wrapped stream. ↩
- C# generics; TypeScript generics ↩