PHpullh
학습 라이브러리/Python/이벤트 드리븐

PYTHON · 디자인패턴

이벤트 드리븐

이벤트 기반 아키텍처로 컴포넌트 간 느슨한 결합을 구현합니다.

디자인패턴고급event-driven이벤트EventBus느슨한 결합

핵심 설명

이벤트 기반 아키텍처로 컴포넌트 간 느슨한 결합을 구현합니다.

Python code

from collections import defaultdict
from dataclasses import dataclass, field
from typing import Callable, Any
from datetime import datetime

@dataclass
class Event:
    name: str
    data: dict
    timestamp: str = field(default_factory=lambda: datetime.now().isoformat())

class EventBus:
    def __init__(self):
        self._handlers: dict[str, list[Callable]] = defaultdict(list)
        self._history: list[Event] = []

    def subscribe(self, event_name: str, handler: Callable):
        self._handlers[event_name].append(handler)

    def publish(self, event_name: str, **data):
        event = Event(event_name, data)
        self._history.append(event)
        for handler in self._handlers.get(event_name, []):
            handler(event)

    def get_history(self) -> list[Event]:
        return self._history.copy()

# 이벤트 핸들러들
bus = EventBus()

bus.subscribe("user.created", lambda e:
    print(f"  [이메일] {e.data['name']}님 환영 메일 발송"))
bus.subscribe("user.created", lambda e:
    print(f"  [분석] 신규 가입 기록"))
bus.subscribe("order.placed", lambda e:
    print(f"  [재고] {e.data['item']} 재고 차감"))
bus.subscribe("order.placed", lambda e:
    print(f"  [알림] 주문 확인 알림"))

# 이벤트 발행
print("=== 사용자 생성 ===")
bus.publish("user.created", name="Alice", email="alice@test.com")
print("\n=== 주문 생성 ===")
bus.publish("order.placed", item="노트북", qty=1)

print(f"\n이벤트 히스토리: {len(bus.get_history())}건")

학습 팁

이벤트 핸들러는 독립적으로 실패해야 합니다. 한 핸들러의 실패가 다른 핸들러에 영향을 주지 않도록 하세요.

주의할 점

이벤트 기반 시스템에서 이벤트 순서에 의존하면 예상치 못한 동작이 발생합니다. 각 핸들러는 독립적이어야 합니다.

자주 묻는 질문

이벤트 드리븐란 무엇인가요?

이벤트 기반 아키텍처로 컴포넌트 간 느슨한 결합을 구현합니다.

이벤트 드리븐 학습 시 주의할 점은 무엇인가요?

이벤트 기반 시스템에서 이벤트 순서에 의존하면 예상치 못한 동작이 발생합니다. 각 핸들러는 독립적이어야 합니다.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.