17.1 Strategy
Defines a family of interchangeable algorithms, encapsulated in separate classes, selected at runtime — the direct implementation of the Open/Closed Principle: adding a new algorithm means adding a new class, never modifying existing conditional logic.
public interface IPricingStrategy
{
decimal CalculatePrice(Product product, Customer customer);
}
public class RegularPricing : IPricingStrategy
{
public decimal CalculatePrice(Product product, Customer customer) => product.BasePrice;
}
public class PremiumPricing : IPricingStrategy
{
public decimal CalculatePrice(Product product, Customer customer) => product.BasePrice * 0.85m;
}
public class PricingService
{
private readonly IDictionary<CustomerTier, IPricingStrategy> _strategies;
public decimal GetPrice(Product product, Customer customer) =>
_strategies[customer.Tier].CalculatePrice(product, customer);
}
// AI-provider selection — a very interview-relevant example
public interface IAIGenerationStrategy { Task<string> GenerateResponseAsync(string prompt); }
public class OpenAIStrategy : IAIGenerationStrategy
{
public async Task<string> GenerateResponseAsync(string prompt) => "Response from GPT-4";
}
public class ClaudeStrategy : IAIGenerationStrategy
{
public async Task<string> GenerateResponseAsync(string prompt) => "Response from Claude";
}
public class AICoPilotService
{
private IAIGenerationStrategy _strategy;
public void SetStrategy(IAIGenerationStrategy strategy) => _strategy = strategy;
public async Task ExecutePrompt(string prompt) =>
Console.WriteLine(await _strategy.GenerateResponseAsync(prompt));
}
# Strategy pattern in Python
from abc import ABC, abstractmethod
class IAIGenerationStrategy(ABC):
@abstractmethod
def generate(self, prompt: str) -> str: ...
class OpenAIStrategy(IAIGenerationStrategy):
def generate(self, prompt: str) -> str:
return call_openai(prompt)
class ClaudeStrategy(IAIGenerationStrategy):
def generate(self, prompt: str) -> str:
return call_claude(prompt)
class AICoPilotService:
def __init__(self, strategy: IAIGenerationStrategy):
self._strategy = strategy # injected — service doesn't know which provider
def set_strategy(self, strategy: IAIGenerationStrategy) -> None:
self._strategy = strategy
def execute_prompt(self, prompt: str) -> str:
return self._strategy.generate(prompt) # doesn't care HOW, just that it works
17.2 Observer / Pub-Sub
A subject maintains a list of dependents (observers) and notifies them automatically of state changes — the foundation of event-driven architecture.
public class StockPriceMonitor
{
public event EventHandler<PriceChangedEventArgs> PriceChanged;
private decimal _price;
public decimal Price
{
get => _price;
set
{
if (_price != value)
{
var old = _price; _price = value;
PriceChanged?.Invoke(this, new PriceChangedEventArgs(old, value));
}
}
}
}
# Observer / Pub-Sub in Python
class EventBus:
def __init__(self):
self._subscribers: dict[str, list] = {}
def subscribe(self, event_type: str, handler) -> None:
self._subscribers.setdefault(event_type, []).append(handler)
def publish(self, event_type: str, payload: dict) -> None:
for handler in self._subscribers.get(event_type, []):
handler(payload)
bus = EventBus()
def send_confirmation_email(payload):
print(f"Emailing customer about order {payload['order_id']}")
def update_analytics(payload):
print(f"Recording order {payload['order_id']} in analytics")
bus.subscribe("OrderCreated", send_confirmation_email)
bus.subscribe("OrderCreated", update_analytics)
bus.publish("OrderCreated", {"order_id": "ord-123"}) # both subscribers notified
Architect framing: “In distributed systems I rely heavily on Observer/Pub-Sub via Kafka or a cloud event bus. Instead of microservices making synchronous HTTP calls to each other — which creates tight coupling and cascading failures — they publish events, and other services subscribe. This decouples the architecture completely and makes it far more resilient to a single consumer being slow or down.”
17.3 Command
Encapsulates a request as an object, letting you parameterize callers, queue/log requests, and support undo — also the foundation of CQRS command handlers and mediator libraries like MediatR.
public record CreateOrderCommand(int CustomerId, List<OrderItem> Items) : IRequest<OrderResult>;
public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, OrderResult>
{
private readonly IOrderRepository _repo;
private readonly IMediator _mediator;
public async Task<OrderResult> Handle(CreateOrderCommand request, CancellationToken ct)
{
var order = new Order(request.CustomerId, request.Items);
await _repo.AddAsync(order);
await _mediator.Publish(new OrderCreatedEvent(order.Id), ct);
return new OrderResult(order.Id, true);
}
}
# Command pattern in Python — encapsulating a request as an object with undo support
from abc import ABC, abstractmethod
class ICommand(ABC):
@abstractmethod
def execute(self) -> None: ...
@abstractmethod
def undo(self) -> None: ...
class ReserveInventoryCommand(ICommand):
def __init__(self, inventory_service, order_id: str, items: list):
self._inventory = inventory_service
self._order_id = order_id
self._items = items
def execute(self) -> None:
self._inventory.reserve(self._order_id, self._items)
def undo(self) -> None:
self._inventory.release(self._order_id)
class CommandInvoker:
"""Executes commands, keeps a history so it can undo the last N on failure."""
def __init__(self):
self._history: list[ICommand] = []
def execute(self, command: ICommand) -> None:
command.execute()
self._history.append(command)
def undo_last(self) -> None:
if self._history:
self._history.pop().undo()
17.4 Chain of Responsibility
Passes a request along a chain of handlers until one handles it — decouples the sender from the specific handler, and lets you compose/reorder handling logic (validation pipelines, middleware) without changing the caller.
public abstract class OrderValidationHandler
{
protected OrderValidationHandler? Next;
public OrderValidationHandler SetNext(OrderValidationHandler next) { Next = next; return next; }
public virtual ValidationResult Handle(Order order) => Next?.Handle(order) ?? ValidationResult.Success();
}
public class StockAvailabilityHandler : OrderValidationHandler
{
public override ValidationResult Handle(Order order)
{
if (!HasStock(order)) return ValidationResult.Fail("Insufficient stock");
return base.Handle(order); // pass to next handler in the chain
}
}
public class CreditLimitHandler : OrderValidationHandler
{
public override ValidationResult Handle(Order order)
{
if (order.Total > order.Customer.CreditLimit) return ValidationResult.Fail("Credit limit exceeded");
return base.Handle(order);
}
}
// Compose the chain
var chain = new StockAvailabilityHandler();
chain.SetNext(new CreditLimitHandler());
var result = chain.Handle(order);
# Chain of Responsibility in Python
from abc import ABC, abstractmethod
from typing import Optional
class OrderValidationHandler(ABC):
def __init__(self):
self._next: Optional["OrderValidationHandler"] = None
def set_next(self, handler: "OrderValidationHandler") -> "OrderValidationHandler":
self._next = handler
return handler
def handle(self, order: dict) -> Optional[str]:
error = self._check(order)
if error:
return error
if self._next:
return self._next.handle(order)
return None
@abstractmethod
def _check(self, order: dict) -> Optional[str]: ...
class StockAvailabilityHandler(OrderValidationHandler):
def _check(self, order: dict) -> Optional[str]:
return None if has_stock(order) else "Insufficient stock"
class CreditLimitHandler(OrderValidationHandler):
def _check(self, order: dict) -> Optional[str]:
return None if order["total"] <= order["credit_limit"] else "Credit limit exceeded"
chain = StockAvailabilityHandler()
chain.set_next(CreditLimitHandler())
error = chain.handle(order) # None if all handlers pass, else the first failure message
17.5 Interview Q&A
Q1: Explain the Strategy pattern and when you would use it.
The Strategy pattern eliminates massive
if/elseorswitchstatements by encapsulating each algorithm in its own class behind a shared interface, letting them be swapped at runtime — a direct implementation of the Open/Closed Principle. A concrete example from AI workflows: swapping the underlying LLM provider based on user tier. Instead of hardcoding provider-specific calls, I define anIAIGenerationStrategyinterface with concreteOpenAIStrategyandClaudeStrategyimplementations; the core service just calls.Generate()and is completely decoupled from which provider is behind it. Adding a new local model tomorrow means writing one new Strategy class — the core domain logic never changes.
Q2: When would you choose Observer/Pub-Sub over a direct method call, and what’s the tradeoff?
Pub-Sub when the publisher shouldn’t need to know or care who’s listening, and when multiple independent consumers need the same fact without the publisher coordinating with each of them — the classic case is publishing
OrderCreatedand letting notification, analytics, and shipping each subscribe independently. The tradeoff is losing the immediacy and simplicity of a direct call — a direct call gives an immediate return value and a clear stack trace on failure; a published event is fire-and-forget, needs its own failure-handling story (dead-letter queues, retries), and requires distributed tracing to reconstruct “what happened” across all the subscribers. I use pub-sub deliberately for cross-service decoupling, not as a default replacement for in-process method calls.
Q3: How is Command different from Strategy — both wrap a unit of behavior behind an interface?
Strategy is about interchangeable algorithms that solve the same kind of problem differently (different pricing calculations, different LLM providers) — you swap which Strategy is active, but each execution is stateless and immediate. Command is about encapsulating a request itself as an object, which lets you queue it, log it, retry it, or undo it — the Command object typically carries the parameters of a specific invocation and often supports an
Undo(). In practice Command underpins CQRS/MediatR-style command handlers and Saga step definitions, where I need to track what was done in order to compensate for it later, which Strategy alone doesn’t give me.
Q4: How would you build a validation pipeline for an order without a giant if/else block, and how does Chain of Responsibility compare to middleware?
Chain of Responsibility — each validation rule (stock availability, credit limit, fraud check) becomes its own handler with a single
Handlemethod that either fails or passes the order to the next handler. The chain is composed once, typically at startup, and can be reordered or extended by adding a handler without touching existing ones. It’s conceptually identical to the ASP.NET Core / Django middleware pipeline pattern — a linear sequence of handlers each deciding whether to short-circuit or pass control onward — the difference is mostly naming: “middleware” in a web framework context, “Chain of Responsibility” as the general GoF pattern name.