Decorator Facade

Decorator + Facade (GoF Structural)

Decorator: "Attach additional responsibilities to an object dynamically." Facade: "Provide a unified interface to a set of interfaces in a subsystem." — GoF


What they share: both are structural

Both patterns compose objects to get new behaviour. The difference is what they compose:


Decorator

Canonical form

from typing import Protocol


class Notifier(Protocol):
    def send(self, msg: str) -> None: ...


class EmailNotifier:                              # ← concrete implementation
    def send(self, msg: str) -> None:
        print(f"EMAIL: {msg}")


class LoggingNotifier:                            # ← Decorator
    def __init__(self, wrapped: Notifier):
        self._wrapped = wrapped

    def send(self, msg: str) -> None:
        print(f"[LOG] sending: {msg!r}")
        self._wrapped.send(msg)                   # ← delegate!
        print("[LOG] sent")


class RetryNotifier:                              # ← Decorator
    def __init__(self, wrapped: Notifier, attempts: int = 3):
        self._wrapped = wrapped
        self._attempts = attempts

    def send(self, msg: str) -> None:
        last_error = None
        for i in range(self._attempts):
            try:
                self._wrapped.send(msg)
                return
            except Exception as e:
                last_error = e
        raise last_error

Usage — stacked:

# email + retry + logging:
notifier = LoggingNotifier(RetryNotifier(EmailNotifier(), attempts=3))
notifier.send("Hello")
# [LOG] sending: 'Hello'
# (3 attempts if needed)
# EMAIL: Hello
# [LOG] sent

Key signs of Decorator:

  1. The wrapper implements the same interface as the wrapped object — LoggingNotifier.send() matches EmailNotifier.send().
  2. It delegates the call to the wrapped object (self._wrapped.send(msg)).
  3. It adds behaviour before or after the delegation.
  4. Stackable — wrappers nest into each other.

Decorator vs Python @decorator

These are two different things that share a name:

GoF Decorator Python @decorator
An object wraps an object A function wraps a function
Preserves the class interface Preserves the function signature
LoggingNotifier(notifier) @with_logging def func()
Standard GoF form Pythonic form of the same idea

Conceptually the same idea: "a wrapper that adds behaviour". Implemented with different mechanisms.

# OOP form
@dataclass
class TimingNotifier:
    wrapped: Notifier
    def send(self, msg):
        start = time.time()
        self.wrapped.send(msg)
        print(f"took {time.time() - start:.2f}s")


# Functional form
def with_timing(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"took {time.time() - start:.2f}s")
        return result
    return wrapper

@with_timing
def send_email(msg): ...

Pick by context: a class with real state → OOP Decorator. A standalone function → @decorator.


Decorator vs Inheritance

LoggingNotifier could be done through inheritance:

class LoggingEmailNotifier(EmailNotifier):       # ← anti-pattern!
    def send(self, msg):
        print(f"[LOG] {msg}")
        super().send(msg)

Problems with inheritance:

Decorator wins:

Decorator is inheritance, only more flexible.


Stack order matters

n1 = LoggingNotifier(RetryNotifier(EmailNotifier()))
# Log fires ONCE for the whole stack (LoggingNotifier wraps Retry + Email)

n2 = RetryNotifier(LoggingNotifier(EmailNotifier()))
# Log fires on EVERY attempt (RetryNotifier wraps Logging + Email)

The difference is subtle but important: "log the whole stack" ≠ "log every attempt". Pick based on what you want to observe.


When to use Decorator

  1. Cross-cutting concerns — logging, caching, retry, security, throttling, metrics.
  2. Behaviour is combined — combinations are hard to predict in advance.
  3. Dynamic selection — at runtime you decide which decorators to enable.

When NOT to use it

  1. One single wrapper — a separate function is simpler.
  2. The stack is always fixed — @dataclass(frozen=True) with all the parameters is enough.
  3. Changing the signature — Decorator should preserve the interface. If you want a new method, that is Adapter or a new class.

Facade

Canonical form

class CheckoutFacade:
    def __init__(
        self,
        repo: OrderRepository,
        payment: PaymentGateway,
        notifier: Notifier,
        inventory: InventoryService,
    ):
        self._repo = repo
        self._payment = payment
        self._notifier = notifier
        self._inventory = inventory

    def checkout(self, order: Order) -> CheckoutResult:
        """One method that hides 4 steps and the order between them."""
        self._inventory.reserve(order.items)
        try:
            tx_id = self._payment.charge(order.total, order.card_token)
        except PaymentDeclined:
            self._inventory.release(order.items)
            raise
        self._repo.save(order, transaction_id=tx_id)
        self._notifier.send(order.customer_email, f"Order #{order.id} confirmed")
        return CheckoutResult(transaction_id=tx_id, success=True)


# The caller — one line:
facade.checkout(order)

Key signs of Facade:

  1. One new interface — checkout() — simpler than four.
  2. Hides the order and interactions between subsystems.
  3. Delegates to the real objects, does not duplicate the logic.
  4. Domain method names — checkout(), cancel(), refund() — not step1(), step2().

Facade vs Adapter

Often confused, because both are wrappers.

Aspect Adapter Facade
Goal Make incompatible interfaces compatible Simplify the complex
Number wrapped Usually one Usually several
API change Old API → new API A new simple API over a complex one
Example LegacyShippingAdapter CheckoutFacade.checkout()

Overlap: sometimes one wrapper plays both roles, adapting and simplifying. That is fine. The name follows the intent.


Facade vs Controller (from GRASP)

Almost the same idea. In FastAPI:

@app.post("/checkout")
def checkout(order: OrderRequest, facade: CheckoutFacade = Depends(get_facade)):
    return facade.checkout(order)

GRASP Controller is a specialised form of Facade for external calls.


When to use Facade

  1. A complex subsystem with 3-5+ components and a non-trivial call order.
  2. The subsystem will be used by many clients — do not let everyone call 5 methods separately.
  3. An API for external use — hides the internals.

When NOT to use it

  1. A subsystem of one or two calls — Facade is another layer with no benefit.
  2. Every client wants its own sequence — Facade locks one.

Anti-patterns

Decorator

1. Decorator that does not preserve the interface

class WeirdNotifier:
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def deliver(self, msg):                      # ← not send!
        ...

This is an Adapter, not a Decorator. Decorator must have the same method.

2. Decorator with side effects on initialisation

class LoggingNotifier:
    def __init__(self, wrapped):
        self._wrapped = wrapped
        print("[LOG] decorator created")          # ← I/O in __init__!

A wrapper should be cheap to construct. The stack A(B(C(D()))) is created often. Every __init__ should be near-instant.

3. Stackable, but the order is always the same

notifier = always_log(always_retry(always_rate_limit(EmailNotifier())))

If the combination is always one, that is not Decorator. It is a fixed sequence. A single class with all those behaviours or a factory function is simpler.

Facade

1. Fat Facade

class GodFacade:
    def checkout(self, order): ...
    def register_user(self, user): ...
    def calculate_pricing(self, items): ...
    def send_marketing_email(self, user): ...
    # 30 more methods

This is a god class wearing the Facade label. Split by use case: CheckoutFacade, RegistrationFacade, and so on.

2. Facade that bypasses the subsystem

class CheckoutFacade:
    def checkout(self, order):
        # 50 lines of business logic right here

If checkout does everything itself, that is not a Facade. It is a fat controller / god class. It should delegate.

3. Facade for the name

class SimpleFacade:
    def do(self, x):
        return self._inner.do(x)                  # ← just forwards

If the wrapper simplifies nothing, it is redundant. Remove it. Call _inner directly.


Decorator + Facade in Python — typical forms

Decorator in libraries:

Facade in Python:


Rules of thumb

  1. Decorator: one interface, many wrappers. The wrapper has the same signature as the wrapped object.
  2. Stack order is part of the design. Logging outside vs inside has different semantics.
  3. Facade: one new method over several subsystems. Simpler API, fixed order.
  4. @decorator (Python) ≠ Decorator (GoF) but they are conceptually the same. Do not confuse names.
  5. Facade overlaps with Controller — Controller is a specialised form.
  6. Decorator does not change the interface. Adapter does. That is the key difference.

One-line summary

Decorator is "another wrapper with the same interface plus extra behaviour". Facade is "one simplified API over a complex subsystem". The first is for cross-cutting concerns. The second is for use-case modelling.