β° All patterns
Decorator
Wrap behaviour in layers to add features without changing it.
01
Explain it like I'm new
Real-life analogy
Gift wrapping
The gift stays the same. You add wrapping paper, then a ribbon, then a card. Each layer adds something, and you can add or remove layers freely.
π© The problem
You want logging, uppercasing and excitement on top of a function, in different combinations, without editing the original or writing a subclass for every combo.
π‘ The pattern
A decorator takes a function (or interface) and returns a new one with the same signature that adds behaviour before or after calling the original.
02
Play with it
An interactive model of the pattern. Click around, nothing can break.
Layers (outermost first). Toggle and reorder them:
- WithLogging
- WithUppercase
- WithExcitement
- WithTruncate(10)
The onion
WithLogging(WithUppercase(WithExcitement(Hello)))("gopher")
π‘ Turn on WithTruncate, then move it above and below WithExcitement. Order changes the result, just like the order of HTTP middleware matters.
03
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press βΆ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
04
When should I use it?
β Reach for it whenβ¦
- β’Cross-cutting concerns: logging, metrics, retries, auth, caching.
- β’HTTP middleware chains.
π« Skip it whenβ¦
- β’Very deep stacks become hard to debug. Keep chains short and named.
πΉ Go tip
This is exactly how net/http middleware works: func Logging(next http.Handler) http.Handler.
π You've already seen it in
net/http middleware, bufio.NewReader(r) wrapping an io.Reader, and gzip.NewWriter(w).
05
Quick check
One question. No pressure.
In WithLogging(WithUppercase(Hello)), which function produces the original string first?
Related: Proxy, Chain of Responsibility, Adapter