Skip to content
BENIBIX Learn

Decorator Pattern

Development🏗️ ArchitectureDesign Patterns

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

The decorator pattern adds a feature to an object by wrapping it in another object with the same interface. The wrapper does its extra work, then passes the call on to the object inside. You can stack wrappers, each adding one thing, like logging or caching. The code that uses the object cannot tell it is wrapped. It is one of the 23 patterns in the 1994 Gang of Four book.

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]
CachedReader has the same read() as the reader it wraps, and adds a cache.
Decorator, top left: each layer adds one thing and keeps the same read method.

Common mistake

Mixing it up with Python's @decorator. That is a language feature for wrapping functions, close in spirit but not the same thing.

Key takeaways

  1. 1
    Same interface. Callers cannot tell.
  2. 2
    Wraps and passes on. Extra work, then the call.
  3. 3
    Stackable. One feature per layer.

Compare