Design patterns jsou ověřená řešení opakujících se problémů. Ne všechny potřebujete, ale měli byste je znát.
Creational¶
Factory Pattern¶
class NotificationFactory: @staticmethod def create(type: str) -> Notification: match type: case ‘email’: return EmailNotification() case ‘sms’: return SMSNotification() case ‘push’: return PushNotification() case _: raise ValueError(f”Unknown type: {type}”)
Behavioral¶
Strategy Pattern¶
from typing import Protocol class SortStrategy(Protocol): def sort(self, data: list) -> list: … class QuickSort: def sort(self, data: list) -> list: return sorted(data) # Simplified class Sorter: def __init__(self, strategy: SortStrategy): self.strategy = strategy def sort(self, data: list) -> list: return self.strategy.sort(data)
Observer Pattern¶
class EventEmitter: def __init__(self): self._listeners = {} def on(self, event, callback): self._listeners.setdefault(event, []).append(callback) def emit(self, event, *args): for cb in self._listeners.get(event, []): cb(*args)
Structural¶
Decorator Pattern (Python native)¶
import functools def retry(max_attempts=3): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(max_attempts): try: return func(*args, **kwargs) except Exception as e: if attempt == max_attempts - 1: raise return wrapper return decorator @retry(max_attempts=3) def fetch_data(url): return requests.get(url).json()
Klíčový takeaway¶
Factory pro vytváření, Strategy pro zaměnitelné algoritmy, Observer pro events, Decorator pro rozšíření. Neoverengineeru.