어댑터 패턴(Adapter Pattern)은 호환되지 않는 인터페이스를 연결하는 구조 패턴이다. 220V-110V 변환 어댑터처럼, 기존 코드를 변경하지 않고 새 인터페이스와 연동한다.
두 가지 구현 방식
| 방식 | 설명 | 특징 |
|---|
| 클래스 어댑터 | 상속으로 구현 | 단일 상속 제약 |
| 객체 어댑터 | 컴포지션으로 구현 | 더 유연함 |
python
# 기존 시스템 (Adaptee)
class OldPaymentGateway:
def make_payment(self, amount_cents: int, currency_code: str) -> bool:
print(f"구 결제 API: {amount_cents}센트, {currency_code}")
return True
# 새 인터페이스 (Target)
class PaymentProcessor:
def pay(self, amount_usd: float) -> bool:
raise NotImplementedError
# 객체 어댑터
class PaymentAdapter(PaymentProcessor):
def __init__(self, old_gateway: OldPaymentGateway):
self._gateway = old_gateway
def pay(self, amount_usd: float) -> bool:
# 인터페이스 변환
amount_cents = int(amount_usd * 100)
return self._gateway.make_payment(amount_cents, "USD")
# 클래스 어댑터
class ClassPaymentAdapter(OldPaymentGateway, PaymentProcessor):
def pay(self, amount_usd: float) -> bool:
return self.make_payment(int(amount_usd * 100), "USD")
# 사용
gateway = OldPaymentGateway()
adapter = PaymentAdapter(gateway)
adapter.pay(29.99)
실전 예시: pandas DataFrame 어댑터
python
import pandas as pd
class DataFrameAdapter:
"""sklearn이 기대하는 형식으로 변환"""
def __init__(self, df: pd.DataFrame, label_col: str):
self.X = df.drop(columns=[label_col]).values
self.y = df[label_col].values
def get_features(self):
return self.X
def get_labels(self):
return self.y
관련 개념