Decorator pattern
medium 45 minDecorator adds behaviour to one object by wrapping it in another with the same interface.
Video lesson · Chapter 1 of 6
Make a prediction
Decorator
1:04Reel
More reels
One idea each, a minute or less.
Decorator vs proxy
0:32Reel
Theory
Read or listen first. About 1 min.
What it is
Decorator is a structural design pattern. An object is put inside another object that has the same interface, forwards calls to it, and adds something before, after or around them.
A decorator is a component and has a component. Because of the first it can be used anywhere the original could. Because of the second it can ask the original. Together they allow decorators around decorators.
The object inside is never changed. Each object can wear its own set of layers.
Why it exists
Subclasses fix a combination when you compile, and the number of combinations doubles with each optional extra.
With decorators each extra is one class, written once, and combinations are made at run time, for one object.
Extras such as logging, caching, retry, buffering and checking stay out of the class that does the real work. That class keeps one reason to change.
A short history
1994
The book Design Patterns describes Decorator among its structural patterns, with scroll bars and borders around a text view as the example.
1996
Java 1.0 ships stream classes that wrap streams:
FilterInputStreamand its subclasses are listed as since 1.0.2003
PEP 318 is created: the @ syntax for decorators of Python functions. It came with Python 2.4.
Words to know
- Component
- The interface shared by the object and its wrappers.
- Concrete component
- The object at the centre.
- Base decorator
- Holds a component and forwards everything.
- Concrete decorator
- Adds one responsibility.
- Forwarding
- Passing a call on to the object inside.
- Layer, chain
- One wrapper, and the whole line of them.
- Transparent
- Clients can not tell a wrapped object from a bare one by calling it.
- Middleware
- A decorator around a request handler.
- Self call
- An object calling its own method. It does not pass through the wrapper.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Call arrives. At the outermost layer
Understand it
Start here
Dressed, but still the same snowman
You want to add something to one object: logging to this service, milk to this coffee, a buffer to this file. Not to all objects of the class, not for ever, and not by editing the class. The Decorator pattern puts the object into another one that looks the same from outside and adds its bit.
However the snowman is dressed, Lee measures in the same way: once around the outside.
A wrapped birthday present is the same idea. A toy, a box around it, paper around the box, a ribbon around the paper. Each layer adds something, nobody changed the toy, and from outside it is still one present that you can hand over.
Four roles
Component
The interface that the client uses:
Coffee,InputStream,HttpClient.Concrete component
The object at the centre:
Espresso,FileInputStream. It does the real work.Decorator
Is a component and has a component. Forwards everything. Usually abstract.
Concrete decorator
Adds one thing before or after forwarding:
Milk,BufferedInputStream.
Why
What goes wrong with subclasses
A coffee shop sells espresso. Then espresso with milk, then with sugar, then with both. With inheritance each combination is a class, and each combination is decided when you compile.
class Espresso: def cost(self): return 200class EspressoMilk(Espresso): def cost(self): return 200 + 60 # new milk priceclass EspressoSugar(Espresso): def cost(self): return 200 + 20class EspressoMilkSugar(Espresso): def cost(self): return 200 + 60 + 20class EspressoMilkCream(Espresso): def cost(self): return 200 + 50 + 70 # forgottenclass EspressoMilkSugarCream(Espresso): def cost(self): return 200 + 60 + 20 + 70print("milk in the first:", EspressoMilk().cost() - Espresso().cost())print("milk in the fourth:", EspressoMilkCream().cost() - 200 - 70)print("double milk: no class for it")The explosion
The design that hurts
1/3One coffee, three toppings
So far so good. Each subclass adds one topping.
extends (is a)
A wrapper per extra
- n decorators and one base
- Each rule in one place
- Chosen at run time, per object
- Any order, any number of times
A subclass per combination
- 2 to the power of n classes
- The same rule in many places
- Fixed when you compile
- No double portions
The idea
Is one, and has one
A decorator implements the interface, so it can stand wherever the original stood. It also holds an object of that interface, so it can ask for the original answer. These two facts together make nesting possible.
The Decorator pattern in general
1/4The interface
The client knows Component and nothing else. It does not need to change when something is wrapped.
usesimplementshas (lives on)extends (is a)
What exists at run time
cost() goes in and comes out
description() does the same with text
Kinds
What a decorator may do around the call
| Place | Example | Code |
|---|---|---|
| Before | check the token, start a clock | check(); return inner.get(x) |
| After | add a price, log the result | return inner.cost() + 50 |
| Around | measure, retry, transaction | try: ... finally: ... |
| Instead | answer from a cache | if x in memo: return memo[x] |
| Change the argument | add a header, encode | inner.send(encrypt(x)) |
| Change the result | decode, cut, sort | return unzip(inner.read()) |
Order
Which layer is outside?
With prices the order does not matter, because addition does not care. With almost everything else it does. Read a chain from the outside: the outer layer sees the request first and the answer last.
| Outside | Inside | Meaning |
|---|---|---|
| Encrypt | Compress | Compress first, then encrypt: small and secret |
| Compress | Encrypt | Encrypted data looks random and hardly gets smaller |
| Retry | Log | One line per attempt |
| Log | Retry | One line per request, attempts hidden |
| Cache | Authorize | A second user may get the first user's answer |
| Authorize | Cache | Everyone is checked, then the cache may answer |
A service needs a cache and a permission check, both as decorators. Which goes outside?
BreaksCache outside, key is the id
- How
Cache(Authorize(service)).- Limit
- Asha's salary is cached. Sam asks for the same id and gets it without any check.
- Choose when
- Never.
WorksCache outside, key is user and id
- How
- The answer is stored per user.
- Limit
- Many more entries, and a permission that was taken away still answers until the entry ends.
- Choose when
- When the answer itself differs per user.
StrongAuthorize outside, cache inside
- How
Authorize(Cache(service)). Every call is checked, the data is shared.- Limit
- The check runs on every call, so it must be cheap.
- Choose when
- The default.
Choosing
When to use it and when not
Use it when
- Extras are optional and combine freely
- They differ per object, or change at run time
- You can not or should not edit the class
- The interface is small
- Concerns such as logging, caching, retry surround the work
Leave it when
- There is one fixed extra: put it in the class
- The interface has thirty methods
- Extras need the inside of the object
- Callers compare identity or ask for the class
- Milk is only a price: then a list of toppings is data
Decorator or something else?
Real cases
| Component | Centre | Decorators |
|---|---|---|
InputStream | file, socket, memory | buffer, unzip, decipher, count |
| HTTP handler | your function | auth, logging, compression |
| HTTP client | socket client | retry, timeout, cache, metrics |
| Widget | text area | scroll bars, border, shadow |
| Collection | list | read only, synchronized, checked |
| Function | your function | @cache, @timer, @retry |
| Repository | SQL | cache, audit, soft delete |
try (DataInputStream in = new DataInputStream( new GZIPInputStream( new BufferedInputStream( new FileInputStream("data.gz"))))) { int value = in.readInt(); // 4 bytes, unzipped, buffered, from disk}Summary
The whole topic in one minute.
Wrap the object in something that is one and has one. Forward everything, add one thing, leave the inside alone. n extras are n classes.
Read a chain from outside: the outer layer sees the request first. Authorize outside cache, buffer next to the slow thing, the layer with extra methods outermost.
In production: build the chain in one place, keep state per service or per request on purpose, close from outside in, and remember that identity, type checks and self calls see through the wrapper.
- A decorator is a component and has a component.
- It adds one thing, forwards the rest, and never changes the object inside.
- n decorators replace 2 to the power of n subclasses.
- The outer layer sees the request first. Order is a decision, not a detail.
- Identity, wide interfaces and closing are the three places where wrappers leak.