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
See it run
Objects at run time: who wraps whom, and what each layer adds.
Operations
Coffee, layer by layer
Wrap an espresso three times, then ask for the price.
Step 1 of 9
Espresso
The concrete component. It costs 200.
Step 1: Espresso
coffee = Espresso()coffee = Milk(coffee)coffee = Sugar(coffee)coffee = WhippedCream(coffee)coffee.cost()class Milk(CoffeeDecorator): def cost(self): return super().cost() + 50- Watch
- The client's arrow
- Result
- 340 cents
The client always holds the outermost layer.
In the real world
The same decorator pattern doing real jobs. Pick one and step through it.
A cache decorator that loads each key once.
Step 1 of 3
Asha asks first
The key is unknown. A promise is stored, and Asha's thread loads.
Step 1: Asha asks first
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Forgetting the assignment
majorThe wrapper is created and thrown away.
WrongMilk(coffee)coffee.cost() # 200Rightcoffee = Milk(coffee)coffee.cost() # 250Repeating the inner value
majorRight for espresso, wrong for anything else.
Wrongclass Milk(CoffeeDecorator): def cost(self): return 250Rightclass Milk(CoffeeDecorator): def cost(self): return super().cost() + 50Cache around the check
criticalA hit gives one user another user's data.
WrongCache(Authorize(service))RightAuthorize(Cache(service))One try around everything
criticalA failing log repeats or hides the payment.
Wrongtry: r = inner.pay(x); log(r)except Exception: return NoneRightr = inner.pay(x)try: log(r)except Exception: errors.add(1)return rClosing the inside
majorThe buffer's last bytes go nowhere.
Wrongout = Buffered(file)file.close()Rightout = Buffered(file)out.close() # flushes, then closes file
Interview tips
Base first
- Forward everything once.
- Refuse a missing inside.
- Keep the interface small.
Order
- Outside sees first.
- Authorize outside cache.
- Buffer next to the disk.
State
- Share on purpose.
- Never lock a slow call.
- Bound every cache.
Know the leaks
- Identity.
- Self calls.
- Extra methods.