디자인 패턴

목표

  • 전략 패턴 사용
  • 옵저버 패턴 사용

1.전략 패턴 (Strategy Pattern)

사용 시점

  • 유사한 기능을 하는 여러 클래스가 존재할 때
    • 예: 다양한 결제 수단 (신용카드, 카카오페이, 토스페이)
    • 예: 다양한 인증 방식 (JWT, OAuth, Basic Auth)
    • 예: 다양한 캐싱 전략 (Redis, Memcached, Local Cache)
    • 예: 다양한 로깅 방식 (File, Console, Cloud)

구현 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from abc import ABC, abstractmethod

# 결제 수단 인터페이스 (Strategy)
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass

# 결제 수단 구현 (Concrete Strategies)
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"신용카드로 {amount}원 결제 완료!")

class KakaoPayPayment(PaymentStrategy):
def pay(self, amount):
print(f"카카오페이로 {amount}원 결제 완료!")

# 결제 프로세서 (Context)
class PaymentProcessor:
def __init__(self, payment_strategy: PaymentStrategy):
self.payment_strategy = payment_strategy

def pay(self, amount):
self.payment_strategy.pay(amount)

# 사용 예시
payment = PaymentProcessor(KakaoPayPayment())
payment.pay(10000)

2.옵저버 패턴 (Observer Pattern)

사용 시점

  • 한 객체의 상태 변화를 다른 객체들에게 알려야 할 때
    • 예: 결제 상태 변경 알림
    • 예: 이벤트 처리 시스템 (버튼 클릭, 키보드 입력)
    • 예: 실시간 데이터 업데이트 (주식 가격, 날씨 정보)
    • 예: 사용자 인터페이스 업데이트 (데이터 변경 시 화면 갱신)

구현 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 옵저버(Observer) 인터페이스
class Notifier:
def send_notification(self, message):
pass

# 알림 방식 구현
class SMSNotifier(Notifier):
def send_notification(self, message):
print(f"📱 SMS: {message}")

class EmailNotifier(Notifier):
def send_notification(self, message):
print(f"📧 Email: {message}")

# 결제 프로세서 (Subject)
class PaymentProcessor:
def __init__(self):
self.notifiers = []

def add_notifier(self, notifier: Notifier):
self.notifiers.append(notifier)

def pay(self, amount):
print(f"💳 {amount}원 결제 완료!")
for notifier in self.notifiers:
notifier.send_notification(f"{amount}원 결제가 완료되었습니다.")

# 사용 예시
payment = PaymentProcessor()
payment.add_notifier(SMSNotifier())
payment.add_notifier(EmailNotifier())
payment.pay(20000)

정리

각 디자인 패턴은 특정 상황에서 코드의 유지보수성과 확장성을 높이는 데 도움을 줍니다. 실제 프로젝트에서는 이러한 패턴들을 적절히 조합하여 사용하는 것이 중요합니다.