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: wraps one object into a new one that does the same plus more.
- Facade: hides many objects behind one that simplifies access.
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:
- The wrapper implements the same interface as the wrapped object —
LoggingNotifier.send()matchesEmailNotifier.send(). - It delegates the call to the wrapped object (
self._wrapped.send(msg)). - It adds behaviour before or after the delegation.
- 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:
- A separate class for every combination (
LoggingEmail,LoggingSms,LoggingSlack—n × m). - You cannot combine them dynamically at runtime.
- Tight coupling to a specific base class.
Decorator wins:
n + mclasses instead ofn × m.- The stack is built at runtime:
wrap = X(Y(Z(notifier))). - Works with any
Notifier.
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
- Cross-cutting concerns — logging, caching, retry, security, throttling, metrics.
- Behaviour is combined — combinations are hard to predict in advance.
- Dynamic selection — at runtime you decide which decorators to enable.
When NOT to use it
- One single wrapper — a separate function is simpler.
- The stack is always fixed —
@dataclass(frozen=True)with all the parameters is enough. - 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:
- One new interface —
checkout()— simpler than four. - Hides the order and interactions between subsystems.
- Delegates to the real objects, does not duplicate the logic.
- Domain method names —
checkout(),cancel(),refund()— notstep1(),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)
- Controller is an HTTP/CLI facade over a use case service.
- Use Case Service is a business facade over domain operations.
- Facade Pattern is the general form.
GRASP Controller is a specialised form of Facade for external calls.
When to use Facade
- A complex subsystem with 3-5+ components and a non-trivial call order.
- The subsystem will be used by many clients — do not let everyone call 5 methods separately.
- An API for external use — hides the internals.
When NOT to use it
- A subsystem of one or two calls — Facade is another layer with no benefit.
- 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:
functools.lru_cache— a caching decorator.contextlib.contextmanager— wraps a generator.- Sentry / OpenTelemetry — auto-instrumenting decorators.
Facade in Python:
requestsis a facade overurllib3+ ssl + connection pooling.subprocess.run()is a facade overPopenand its settings.pathlib.Pathis a facade overos.path+os+shutil.
Rules of thumb
- Decorator: one interface, many wrappers. The wrapper has the same signature as the wrapped object.
- Stack order is part of the design. Logging outside vs inside has different semantics.
- Facade: one new method over several subsystems. Simpler API, fixed order.
@decorator(Python) ≠ Decorator (GoF) but they are conceptually the same. Do not confuse names.- Facade overlaps with Controller — Controller is a specialised form.
- 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.