🏗️Decorator Pattern
Also known as Decorator Design Pattern, Decorator Object
An object wrapped in another that adds a feature. It still looks the same.
Think of it like
It is like a coat on top of a jumper. You get warm, and the jumper does not change.
Example
Jack wraps his data reader in a caching decorator, then in a logging one. The rest of the app still calls read() and never knows.
Why it matters
You add features without changing code that already works, and mix them in any order. It saves writing a new subclass for every mix.
Definition
Example code
python
class CachedReader:
def __init__(self, inner):
self.inner, self.cache = inner, {}
def read(self, key):
if key not in self.cache:
self.cache[key] = self.inner.read(key)
return self.cache[key]Common mistake
Key takeaways
- 1Same interface. Callers cannot tell.
- 2Wraps and passes on. Extra work, then the call.
- 3Stackable. One feature per layer.