16.1 Decorator
Adds behavior to an object dynamically without modifying it or affecting sibling instances — the cleanest way to layer cross-cutting concerns (logging, retry, caching, telemetry) onto a core service without violating SRP.
public interface IMessageService { Task SendAsync(Message message); }
public class BasicMessageService : IMessageService
{
public Task SendAsync(Message message) => /* send logic */;
}
public class LoggingMessageService : IMessageService
{
private readonly IMessageService _inner;
private readonly ILogger _logger;
public LoggingMessageService(IMessageService inner, ILogger logger)
{ _inner = inner; _logger = logger; }
public async Task SendAsync(Message message)
{
_logger.LogInformation("Sending message to {Recipient}", message.To);
await _inner.SendAsync(message);
_logger.LogInformation("Message sent successfully");
}
}
public class RetryMessageService : IMessageService
{
private readonly IMessageService _inner;
public async Task SendAsync(Message message)
{
for (int i = 0; i < 3; i++)
{
try { await _inner.SendAsync(message); return; }
catch when (i < 2) { await Task.Delay(1000 * (i + 1)); }
}
}
}
// DI registration — decorators stack in order
services.AddScoped<IMessageService, BasicMessageService>();
services.Decorate<IMessageService, RetryMessageService>();
services.Decorate<IMessageService, LoggingMessageService>();
# Decorator pattern in Python — object-based composition (not the @decorator syntax)
from abc import ABC, abstractmethod
import time
class IAIService(ABC):
@abstractmethod
def generate(self, prompt: str) -> str: ...
class CoreAIService(IAIService):
def generate(self, prompt: str) -> str:
return call_llm_api(prompt) # the actual generation logic, kept clean
class RetryDecorator(IAIService):
def __init__(self, inner: IAIService, max_retries: int = 3):
self._inner = inner
self._max_retries = max_retries
def generate(self, prompt: str) -> str:
for attempt in range(self._max_retries):
try:
return self._inner.generate(prompt)
except Exception:
if attempt == self._max_retries - 1:
raise
time.sleep(2 ** attempt)
class TelemetryDecorator(IAIService):
def __init__(self, inner: IAIService):
self._inner = inner
def generate(self, prompt: str) -> str:
start = time.time()
result = self._inner.generate(prompt)
log_metric("ai_generation_latency_ms", (time.time() - start) * 1000)
return result
# Compose: core service wrapped in retry, wrapped in telemetry
service: IAIService = TelemetryDecorator(RetryDecorator(CoreAIService()))
service.generate("Summarize this document")
16.2 Facade
Provides a simplified interface to a larger, complex subsystem — invaluable when integrating with a legacy monolith or a messy third-party SDK.
public class OrderFacade
{
private readonly IInventoryService _inventory;
private readonly IPaymentService _payment;
private readonly IShippingService _shipping;
private readonly INotificationService _notifications;
public async Task<OrderResult> PlaceOrderAsync(OrderRequest request)
{
var stock = await _inventory.ReserveAsync(request.Items);
if (!stock.Success) return OrderResult.OutOfStock(stock.UnavailableItems);
var payment = await _payment.ChargeAsync(request.PaymentDetails, request.Total);
if (!payment.Success)
{
await _inventory.ReleaseAsync(stock.ReservationId);
return OrderResult.PaymentFailed(payment.Error);
}
var shipment = await _shipping.CreateShipmentAsync(request.Address, request.Items);
await _notifications.SendOrderConfirmationAsync(request.CustomerId, shipment.TrackingId);
return OrderResult.Success(shipment.TrackingId);
}
}
# Facade in Python — hides a messy legacy subsystem behind a clean interface
class LegacyMainframeOrderFacade:
"""Clean modern interface over an undocumented legacy order subsystem."""
def __init__(self, legacy_client):
self._legacy = legacy_client
def place_order(self, order: dict) -> dict:
# Internally deals with the legacy system's fixed-width record format,
# session-based auth, and multi-step COMMIT protocol — callers never see it.
session = self._legacy.open_session(order["customer_id"])
record = self._to_legacy_record(order)
self._legacy.submit_record(session, record)
result = self._legacy.commit(session)
self._legacy.close_session(session)
return {"order_id": result.confirmation_number, "status": "placed"}
def _to_legacy_record(self, order: dict) -> str:
return f"{order['customer_id']:<10}{order['total']:>10.2f}"
16.3 Adapter
Converts the interface of an existing class into another interface clients expect — the classic tool for integrating an incompatible third-party or legacy API without changing either side.
// Target interface our app code expects
public interface IPaymentGateway { Task<PaymentResult> ChargeAsync(decimal amount, string token); }
// Adaptee — a third-party SDK with an incompatible interface we don't own
public class LegacyPaymentSdk
{
public LegacyChargeResponse ProcessCharge(int cents, string cardToken) => /* ... */;
}
// Adapter — bridges the incompatible interface to the one our app expects
public class LegacyPaymentGatewayAdapter : IPaymentGateway
{
private readonly LegacyPaymentSdk _legacy;
public LegacyPaymentGatewayAdapter(LegacyPaymentSdk legacy) => _legacy = legacy;
public Task<PaymentResult> ChargeAsync(decimal amount, string token)
{
var response = _legacy.ProcessCharge((int)(amount * 100), token);
return Task.FromResult(new PaymentResult(response.Success, response.ReferenceId));
}
}
# Adapter pattern in Python
class IPaymentGateway:
def charge(self, amount: float, token: str) -> dict: ...
class LegacyPaymentSdk:
"""Third-party SDK we don't control — takes cents, returns a different shape."""
def process_charge(self, cents: int, card_token: str) -> dict:
return {"ok": True, "ref": "TXN123"}
class LegacyPaymentGatewayAdapter(IPaymentGateway):
def __init__(self, legacy: LegacyPaymentSdk):
self._legacy = legacy
def charge(self, amount: float, token: str) -> dict:
response = self._legacy.process_charge(int(amount * 100), token)
return {"success": response["ok"], "reference_id": response["ref"]}
16.4 Proxy
Provides a stand-in for another object to control access to it — common uses: caching, lazy loading, access control, remote invocation.
public class CachedProductRepository : IProductRepository
{
private readonly IProductRepository _inner;
private readonly IMemoryCache _cache;
public async Task<Product> GetByIdAsync(int id) =>
await _cache.GetOrCreateAsync($"product:{id}", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return await _inner.GetByIdAsync(id);
});
}
# Proxy pattern in Python — caching proxy over a repository
class CachedProductRepository:
def __init__(self, inner_repo, cache):
self._inner = inner_repo
self._cache = cache
def get_by_id(self, product_id: str):
cached = self._cache.get(f"product:{product_id}")
if cached is not None:
return cached
product = self._inner.get_by_id(product_id) # delegate to the real subject
self._cache.set(f"product:{product_id}", product, ttl=600)
return product
16.5 Sidecar
An infrastructure-level structural pattern (covered in depth in Part 2, Section 10): a helper container deployed alongside a main container in the same pod, sharing its network/lifecycle, handling cross-cutting concerns (proxying, logging, config refresh) without the main application knowing the sidecar exists.
# Sidecar pattern — Envoy proxy alongside the main application container
spec:
containers:
- name: order-api # main container — business logic only
image: order-api:v1.2.3
- name: envoy-sidecar # sidecar — intercepts all traffic transparently
image: envoyproxy/envoy:v1.28
16.6 Interview Q&A
Q1: When would you use Decorator vs Proxy vs Adapter vs Facade — they all “wrap” another object?
They wrap for different reasons. Decorator adds new behavior to an object while preserving its interface, and decorators are meant to be stacked (retry, then logging, then telemetry, all around the same core interface). Proxy controls access to an object — the interface stays identical, and the proxy’s job is caching, lazy loading, or access control rather than adding new capability. Adapter makes one incompatible interface look like another that the caller expects — it’s a translation layer, typically not stackable, used at integration boundaries. Facade simplifies a whole subsystem of many objects into one simple entry point, rather than wrapping a single object. In legacy modernization work I typically use them together: a Facade in front of the legacy subsystem, with an Adapter or two behind it translating specific incompatible calls, and a Proxy/Decorator layer for cross-cutting concerns like caching and retries on the new clean interface.
Q2: How would you use the Decorator pattern for cross-cutting concerns when integrating an AI SDK?
Rather than cluttering the core generation logic with retry handling or telemetry, I define a clean
IAIServiceinterface with just aGeneratemethod, implement the core call in one class, and then wrap it in aRetryDecoratorand aTelemetryDecorator, composed via dependency injection (or manual composition in Python). Each decorator implements the same interface and delegates to the wrapped instance, adding its one concern before/after the call. This keeps the core generation logic perfectly clean and testable in isolation, while still satisfying enterprise requirements like retries and observability — and I can add or remove a concern by adding or removing one decorator in the composition, without touching the others.
Q3: You’re modernizing a legacy monolith. How does the Facade pattern fit into your migration strategy?
The Facade is my first step, before the Strangler Fig pattern kicks in. I create a clean, modern interface that acts as a Facade over the messy, undocumented legacy subsystem — new code only ever talks to the Facade, never to the legacy internals directly. This immediately stops the legacy technical debt from bleeding into new code, and it isolates the blast radius: because the rest of the system only depends on the Facade’s contract, I can safely rewrite what’s behind it — one legacy component at a time, potentially even service by service under the Strangler Fig approach — without breaking any of the callers.