The Design Patterns Engineer applies the right pattern at the right time. The most common mistake is pattern over-engineering - adding a factory, strategy, and observer to code that would be simpler as a switch statement. Patterns solve recurring design problems; they are a vocabulary for communication and a library of proven solutions, not a checklist to apply to every codebase.
Strategy Pattern - Replace Conditionals
// ❌ Before: adding new payment methods requires modifying this function
function processPayment(method: string, amount: number) {
if (method === 'stripe') { /* ... */ }
else if (method === 'paypal') { /* ... */ }
else if (method === 'crypto') { /* ... */ }
}
// ✅ After: Strategy pattern - new payment methods extend without modifying
interface PaymentStrategy {
process(amount: number): Promise<PaymentResult>;
}
class StripeStrategy implements PaymentStrategy {
async process(amount: number) { return stripe.charge(amount); }
}
class PayPalStrategy implements PaymentStrategy {
async process(amount: number) { return paypal.createOrder(amount); }
}
class PaymentProcessor {
constructor(private strategy: PaymentStrategy) {}
process(amount: number) { return this.strategy.process(amount); }
}
// Open for extension, closed for modification (OCP)
Observer Pattern - Event-Driven Decoupling
type EventMap = { 'order.created': Order; 'user.registered': User };
type EventKey = keyof EventMap;
class EventEmitter<T extends Record<string, any>> {
private listeners = new Map<keyof T, Set<Function>>();
on<K extends keyof T>(event: K, handler: (data: T[K]) => void) {
if (!this.listeners.has(event)) this.listeners.set(event, new Set());
this.listeners.get(event)!.add(handler);
return () => this.listeners.get(event)?.delete(handler); // Returns unsubscribe fn
}
emit<K extends keyof T>(event: K, data: T[K]) {
this.listeners.get(event)?.forEach(h => h(data));
}
}
const bus = new EventEmitter<EventMap>();
// Services subscribe without knowing about each other
bus.on('order.created', (order) => sendConfirmationEmail(order));
bus.on('order.created', (order) => updateInventory(order));
bus.on('order.created', (order) => triggerFulfillment(order));
Decorator Pattern - Add Behaviour Without Subclassing
// Add logging and caching to any repository without modifying it
class CachingOrderRepository implements IOrderRepository {
constructor(
private inner: IOrderRepository,
private cache: Cache,
) {}
async findById(id: string) {
const cached = await this.cache.get(`order:${id}`);
if (cached) return JSON.parse(cached) as Order;
const order = await this.inner.findById(id);
await this.cache.set(`order:${id}`, JSON.stringify(order), { ttl: 300 });
return order;
}
}
const repo = new CachingOrderRepository(new PostgresOrderRepository(pool), redisCache);