Decorator
Intent
Wrap an object in add-on layers that extend its description and cost, keeping the base untouched and add-ons freely combinable.
Motivation
A cafe sells black coffee for $2, with milk and sugar as add-ons. Baking every combination into subclasses (milky coffee, sweet coffee, milky-sweet coffee) explodes with each new extra, and editing the base for every topping risks breaking the plain drink. A decorator wraps any coffee: milk adds its label and price around the inner drink, sugar does the same, so plain and loaded drinks share one composable chain.
Structure
flowchart LR Client --> Drink[Coffee Contract] Drink --> Plain[Black Coffee] Drink --> Milk[Milk Add-on] Drink --> Sugar[Sugar Add-on] Milk --> Drink Sugar --> Drink
- Component (Coffee) — the shared drink contract with description and cost steps.
- Concrete component (Black Coffee) — the plain $2 base drink.
- Decorators (Milk, Sugar) — hold an inner coffee and extend its description and cost.
Consequences
- Benefit: add-ons combine in any order at runtime with no subclass explosion; the base never changes.
- Cost / trade-off: long chains are harder to inspect than one flat object, and order-sensitive add-ons can surprise.
Basic Recap
Decorator adds behavior around an object while preserving the interface callers already use. Decorators can be layered, so independent capabilities such as metrics, authentication, or caching compose without a subclass for every stack. Each wrapper normally delegates to an inner component and contributes work before or after that call. Composition order becomes part of the behavior and must be designed rather than treated as incidental wiring.
Complex Scenario
An internal HTTP client starts with a minimal transport and is decorated with authentication, retries, caching, and metrics. Application services see only the standard client interface regardless of the stack selected for an endpoint. The team must decide whether retries sit outside authentication so refreshed headers are generated per attempt, and whether metrics measure each attempt or the whole logical request. Those semantics come from wrapper placement, not from the base transport.
Edge cases
- Retries: A retry decorator inside a cache may bypass caching on later attempts, while one outside it may repeat cache failures; the desired behavior needs an explicit sequence.
- Concurrency: Reusing one decorator with per-request mutable fields can mix headers and timing data, so request state belongs in invocation context.
- Partial failure: A response received before a metrics backend fails should not turn into a failed business request unless observability is deliberately made mandatory.
A composition root should name the full stack and document its order instead of letting each module add another invisible wrapper.
Sketch (illustrative pseudocode, not runnable):
transport = HttpTransport()
attempts = MetricsDecorator(
AuthDecorator(transport, tokenSource),
scope = PER_ATTEMPT
)
logical = MetricsDecorator(
RetryDecorator(attempts, retryPolicy),
scope = PER_REQUEST
)
client = CacheDecorator(logical, cachePolicy)
response = client.send(request)
# Authentication is refreshed per attempt; request metrics surround retries.
When to Use / When Not to Use
Use when:
- Features layer onto a base in arbitrary combinations chosen at runtime.
- You want to extend behavior without subclassing or editing the base.
Avoid when:
- Combinations are fixed and few — plain variants or parameters are clearer than chains.
- Add-on order silently changes meaning and callers cannot be trusted to order correctly.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/decorator/examples/dart/decorator/examples/go/decorator/examples/rust/decorator/
Expected outcome: the plain coffee prints at $2 and the milk-plus-sugar drink prints at $3.
Anti-pattern / Failure Mode
-
Misuse: Stacking decorators until no one knows the effective behavior.
-
Review signal: Order-dependent decorator stacks with surprising interactions.
-
Misuse symptom: Critical business rules hide in long wrapper stacks, and changing one decorator’s position silently changes security or consistency. Decorators that expose new required methods also force callers to downcast, defeating transparent substitution.
-
Review signal: Look for anonymous chains assembled in several places, decorators with different interface behavior, and tests that exercise only one wrapper at a time. Duplicate metric counts, surprising cache hits, and authentication traces with stale tokens are operational clues that ordering assumptions were never made explicit.
Related
- Composite — wrappers vs trees.
- Proxy — add duties vs control access to the same interface.
- Open/Closed — extend behavior without editing the component.
Exercise
Add a whipped-cream decorator costing $2. A black coffee with cream must print $4, and stacking cream twice must print $6, with no edits to existing add-ons.
Self-check
- Where does the extra price live?
Answer
In each decorator — it adds its own amount around the inner drink’s cost. - Decorator vs subclassing: what changed?
Answer
Combinations compose at runtime by nesting instead of being frozen as classes. - What is the main debugging risk?
Answer
Deep chains hide which layer contributed what; order and identity get harder to trace.