Python 디자인 패턴

Adapter Pattern in Python

Make an old or third-party class fit the interface your code expects, without changing that class.

  • 고급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Incompatible interfaces
  • Wrapping the old object
  • Translating calls and data
pay(25)
  1. 1client.pay(25)The interface the client knows
  2. 2PaymentAdapterTranslates the call
  3. 3legacy.make_payment(...)The old interface
  4. 4PAY 25.00Result

A translator between two interfaces

Adapter는 인터페이스가 맞지 않는 두 구성 요소가 함께 동작하도록 어댑터 역할을 하는 디자인 패턴입니다. 여행할 때 쓰는 전원 플러그 어댑터처럼, 오래된 클래스나 외부 라이브러리를 코드 수정 없이 쓸 수 있게 해 줍니다.

핵심 포인트

  1. The client calls pay(amount).
  2. The legacy class only offers send_payment(cents).
  3. The adapter implements pay() and calls the legacy method with converted values.

언제 사용하나요?

  • 검증된 구조로 반복되는 객체 설계 문제를 해결합니다.
  • 책임을 분리하여 코드를 더 쉽게 확장하고 테스트할 수 있게 합니다.
  • 팀에서 아키텍처를 논의할 때 공통 설계 용어를 사용합니다.

예제 코드

코드 실행 →
main.py
class LegacyGateway:
    # Adapter: wrap an incompatible API with the expected interface.
    def make_payment(self, cents):
        return f"PAY {cents / 100:.2f}"


class PaymentAdapter:
    def __init__(self, gateway):
        self.gateway = gateway

    def pay(self, dollars):
        # Translate both the method name and amount format.
        return self.gateway.make_payment(round(dollars * 100))


gateway = PaymentAdapter(LegacyGateway())
print(gateway.pay(25))
이 예제의 실행 버튼 만들기

실행 결과

PAY 25.00

코드 설명

LegacyGateway 클래스는 센트 단위 금액을 받는 make_payment() 메서드만 제공하지만, 새 코드는 pay()를 호출하고 싶어 합니다. PaymentAdapter 클래스는 LegacyGateway를 감싸서 pay() 호출을 올바른 단위의 make_payment()로 바꿔 주므로 결과는 PAY 25.00입니다.

값을 변경하고 Python 설치 없이 CodeUtility 온라인 Python 컴파일러에서 실행하세요.

연습 문제

아래 제안을 따라 코드를 바꿔 보세요. 코드를 직접 고치고 결과를 확인하면 읽기만 할 때보다 레슨을 훨씬 잘 이해할 수 있습니다.

  1. 패턴 구조를 유지하면서 예제 도메인을 바꿔 보세요.
  2. 패턴을 더 단순한 구현과 비교하고 장단점을 설명하세요.
  3. 다른 구현을 추가하기 전에 각 참여 요소에 대한 테스트를 작성하세요.
Python 컴파일러에서 실행 →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지